本博客讲了一段代码,显示多线程时候,临界区域如果不上锁会发生的问题。
加入头文件#include < thread >就可以使用多线程了,加入头文件#include < mutex >,就可以使用锁了。在多线程中使用lambda,看上去十分”酷炫“。更多关于C++11的lambda
Talk is cheap, show me the code
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
using namespace std;
struct Counter
{
mutex m;
int value;
Counter() : value(0){};
void increment()
{
m.lock();
++value; // 临界区域
m.unlock();
}
};
int main()
{
Counter counter;