1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | static mutex g_mutex1, g_mutex2; static void inc1(int *p ){ for(int i = 0; i < COUNT; i++){ g_mutex1.lock(); (*p)++; g_mutex2.lock(); // do something. g_mutex2.unlock(); g_mutex1.unlock(); } } static void inc2(int *p ){ for(int i = 0; i < COUNT; i++){ g_mutex2.lock(); g_mutex1.lock(); (*p)++; g_mutex1.unlock(); // do other thing. g_mutex2.unlock(); } } void threadMutex(void){ int a = 0; thread ta( inc1, &a); thread tb( inc2, &a); ta.join(); tb.join(); cout << "a=" << a << endl; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | static mutex g_mutex1, g_mutex2; static voi inc1(int *p ){ for(int i = 0; i < COUNT; i++){ g_mutex1.lock(); (*p)++; g_mutex1.unlock(); g_mutex2.lock(); // do something. g_mutex2.unlock(); } } static void inc2(int *p ){ for(int i = 0; i < COUNT; i++){ g_mutex2.lock(); // do other thing. g_mutex2.unlock(); g_mutex1.lock(); (*p)++; g_mutex1.unlock(); } } void threadMutex(void){ int a = 0; thread ta( inc1, &a); thread tb( inc2, &a); ta.join(); tb.join(); cout << "a=" << a << endl; } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |