溫馨提示×

c++分支如何進行并發控制

c++
小樊
93
2024-11-24 15:43:58
欄目: 編程語言

在C++中,可以使用多種方法進行分支并發控制。以下是一些建議:

  1. 使用互斥鎖(std::mutex):互斥鎖可以確保在同一時刻只有一個線程訪問共享資源。當一個線程獲得鎖時,其他線程必須等待直到鎖被釋放。
#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx;
int shared_resource = 0;

void thread_func(int id) {
    for (int i = 0; i < 1000; ++i) {
        mtx.lock();
        shared_resource++;
        mtx.unlock();
    }
}

int main() {
    std::thread t1(thread_func, 1);
    std::thread t2(thread_func, 2);

    t1.join();
    t2.join();

    std::cout << "Shared resource: " << shared_resource << std::endl;

    return 0;
}
  1. 使用原子操作(std::atomic):原子操作是一種特殊的操作,它可以在不使用鎖的情況下保證線程安全。原子操作是不可中斷的,因此它們可以避免死鎖和其他并發問題。
#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> shared_resource(0);

void thread_func(int id) {
    for (int i = 0; i < 1000; ++i) {
        shared_resource++;
    }
}

int main() {
    std::thread t1(thread_func, 1);
    std::thread t2(thread_func, 2);

    t1.join();
    t2.join();

    std::cout << "Shared resource: " << shared_resource.load() << std::endl;

    return 0;
}
  1. 使用條件變量(std::condition_variable):條件變量可以用于線程間的同步,它們允許一個線程等待某個條件成立,而另一個線程在條件滿足時通知等待的線程。
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

std::mutex mtx;
std::condition_variable cv;
int shared_resource = 0;
bool ready = false;

void thread_func(int id) {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, [] { return ready; });

    for (int i = 0; i < 1000; ++i) {
        shared_resource++;
    }
}

int main() {
    std::thread t1(thread_func, 1);
    std::thread t2(thread_func, 2);

    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    cv.notify_all();

    t1.join();
    t2.join();

    std::cout << "Shared resource: " << shared_resource << std::endl;

    return 0;
}

這些方法可以根據具體需求進行組合使用,以實現更復雜的并發控制策略。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女