1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static void inc(int *p ){ for(int i = 0; i < COUNT; i++){ (*p)++; } } void threadDataRacing(void){ int a = 0; thread ta( inc, &a); thread tb( inc, &a); ta.join(); tb.join(); cout << "a=" << a << endl; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | static void inc(atomic<int> *p ){ for(int i = 0; i < COUNT; i++){ (*p)++; } } void threadDataRacing(void){ atomic<int> a(0) ; thread ta( inc, &a); thread tb( inc, &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 | static mutex g_mutex; static void inc(int *p ){ for(int i = 0; i < COUNT; i++){ lock_guard<mutex> _(g_mutex); (*p)++; } } void threadLockGuard(void){ int a = 0; thread ta( inc, &a); thread tb( inc, &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 | static mutex g_mutex; static void inc(int *p ){ thread_local int i; // TLS 变量 for(; i < COUNT; i++){ g_mutex.lock(); (*p)++; g_mutex.unlock(); } } void threadMutex(void){ int a = 0; thread ta( inc, &a); thread tb( inc, &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 | #include <thread> #include <iostream> #include <condition_variable> using namespace std; mutex m; condition_variable cv; void threadCondVar(void){ # define THREAD_COUNT 10 thread** t = new thread*[THREAD_COUNT]; int i; for(i = 0; i < THREAD_COUNT; i++){ t = new thread( [](int index){ unique_lock<mutex> lck(m); cv.wait_for(lck, chrono::hours(1000)); cout << index << endl; }, i ); this_thread::sleep_for( chrono::milliseconds(50)); } for(i = 0; i < THREAD_COUNT; i++){ lock_guard<mutex> _(m); cv.notify_one(); } for(i = 0; i < THREAD_COUNT; i++){ t->join(); delete t; } delete t; } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |