我有一组C++函数:
funcB(){};
funcC(){};
funcA()
{
funcB();
funcC();
}
Run Code Online (Sandbox Code Playgroud)
现在,我想使funcA原子,即funcB和funcC调用内funcA应自动执行.有没有办法实现这个目标?
Rob*_*obᵩ 11
一种方法是使用新的(C++ 11)功能std::mutex和std::lock_guard.
对于每个受保护资源,您实例化一个全局std::mutex; 然后,每个线程根据需要通过创建一个锁定该互斥锁std::lock_guard:
#include <thread>
#include <iostream>
#include <mutex>
#include <vector>
// A single mutex, shared by all threads. It is initialized
// into the "unlocked" state
std::mutex m;
void funcB() {
std::cout << "Hello ";
}
void funcC() {
std::cout << "World." << std::endl;
}
void funcA(int i) {
// The creation of lock_guard locks the mutex
// for the lifetime of the lock_guard
std::lock_guard<std::mutex> l(m);
// Now only a single thread can run this code
std::cout << i << ": ";
funcB();
funcC();
// As we exit this scope, the lock_guard is destroyed,
// the mutex is unlocked, and another thread is allowed to run
}
int main () {
std::vector<std::thread> vt;
// Create and launch a bunch of threads
for(int i =0; i < 10; i++)
vt.push_back(std::thread(funcA, i));
// Wait for all of them to complete
for(auto& t : vt)
t.join();
}
Run Code Online (Sandbox Code Playgroud)
笔记:
funcA可以调用funcB或funcC不调用funcA设置的锁.funcA.