线程冲突学习

https://segmentfault.com/a/1190000007304644,这个举的例子非常好,容易理解。

1.线程冲突

线程间共享进程的资源,在访问时可能会出现 线程冲突、内存一致性错误(这个我还不知道是什么。)解决的方法是线程同步。

当两个运行在不同线程的操作,作用在同一个数据上,会发生线程冲突 (Thread interference)

这也意味着,两个操作分别由多个步骤组成,且两个操作同时执行,会导致步骤交叠。

2.例子

链接中的例子讲的很好。

3.另一个例子

#include<thread>  
#include<mutex>  
using namespace std;  
const int N = 100000000;  
int num(0);  
mutex m;  
void run()  
{  
    for (int i = 0; i < N; i++)  
    {  
        m.lock();  
        num++;  
        m.unlock();  
    }  
}  
int main()  
{  
    clock_t start = clock();  
    thread t1(run);  
    thread t2(run);  
    t1.join();  
    t2.join();  
    clock_t end = clock();  
    cout << "num=" << num << ",用时 " << end - start << " ms" << endl;  
    return 0;  
}  
运行结果:  
num=137887709,用时 1205 ms

可以看到N并没有达到2+++,按照2中的解释,那么就是t1和t2同时将i去了出来,然后分别都++了,之后放入了内存,那么i就会变为+2的结果,那么num的循环次数就会减少。更改为这样就可:

    thread t1(run);
    t1.join();
    thread t2(run);
    t2.join();

这是什么原理呢?

原文地址:https://www.cnblogs.com/BlueBlueSea/p/13888666.html