线程冲突学习

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

通过运行结果看到num并没有达到200000000,是线程t1和t2同时将i了出来,然后分别都++了,之后放入了内,那么i就会变为+2的结果,那么for循环次数就会减少。更改为这样就可:

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

这种方式是线程串行运行。

posted @ 2020-10-28 00:46  lypbendlf  阅读(148)  评论(0编辑  收藏  举报