不合理的设定临界区域,会让线程的调用失去意义。
代码一:
#include <iostream> #include <thread> #include <mutex> using namespace std; mutex m_lock; void workFun(int index) { for (int i = 0; i < 100; i++) { m_lock.lock(); //临界区域-开始 cout << index << " child thread " << i << endl; //临界区域-结束 m_lock.unlock(); } }//抢占式 int main() { thread t[3]; for (int n = 0; n<3; n++) { t[n] = thread(workFun, n); } for (int n = 0; n<3; n++) { t[n].join(); } for (int i = 0; i<4; i++) cout << "i am main thread " << i << endl; return 0; }
代码二:
#include <iostream> #include <thread> #include <mutex> using namespace std; mutex m_lock; void workFun(int index) { m_lock.lock(); //临界区域-开始 for (int i = 0; i < 100; i++) { cout << index << " child thread " << i << endl; } //临界区域-结束 m_lock.unlock(); }//抢占式 int main() { thread t[3]; for (int n = 0; n<3; n++) { t[n] = thread(workFun, n); } for (int n = 0; n<3; n++) { t[n].join(); } for (int i = 0; i<4; i++) cout << "i am main thread " << i << endl; return 0; }
代码二,会让 t[0] t[1] t[2] 这三个线程不再并行,而是顺序执行。这样就失去了调用线程的意义。