在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;
}
這些方法可以根據具體需求進行組合使用,以實現更復雜的并發控制策略。