C++ 多线程之临界区

来源:互联网 发布:localstorage存储数据 编辑:程序博客网 时间:2024/05/16 12:26

关于C++临界区Critical Sections http://blog.sina.com.cn/s/blog_8eee7fb601012omv.html中将的很清楚了

在多线程中,我们看一下使用CRITICAL_SECTION和不使用CRITICAL_SECTION的差异:

struct MyStruct{int a;int b;};MyStruct s;CRITICAL_SECTION cs;void funcPrint(){int count = 0;while (count < 20){count++;EnterCriticalSection(&cs);cout << s.a << " " << s.b << endl;LeaveCriticalSection(&cs);Sleep(1000);}}void funAdd(){int count = 0;while (count < 20){count++;EnterCriticalSection(&cs);s.a++;Sleep(400); s.b++;LeaveCriticalSection(&cs);Sleep(500);}}int main(){s.a = 0;s.b = 0;InitializeCriticalSection(&cs);std::thread t(funcPrint);std::thread t2(funAdd);t.join(); t2.join();return 0;}


struct MyStruct{int a;int b;};MyStruct s;CRITICAL_SECTION cs;void funcPrint(){int count = 0;while (count < 20){count++;//EnterCriticalSection(&cs);cout << s.a << " " << s.b << endl;//LeaveCriticalSection(&cs);Sleep(1000);}}void funAdd(){int count = 0;while (count < 20){count++;//EnterCriticalSection(&cs);s.a++;Sleep(400); s.b++;//LeaveCriticalSection(&cs);Sleep(500);}}int main(){s.a = 0;s.b = 0;InitializeCriticalSection(&cs);std::thread t(funcPrint);std::thread t2(funAdd);t.join(); t2.join();getchar();return 0;}


没有使用临界区的时候就会在两个线程中操作s时产生混乱。

其中join函数就是链接被调线程与主调线程,在join之后执行的代码都是在被调线程执行完成后才执行。

1 0
原创粉丝点击