在C++中,可以使用多种方法进行分支并发控制。以下是一些建议:
#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;
}
#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;
}
#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;
}
这些方法可以根据具体需求进行组合使用,以实现更复杂的并发控制策略。