【发布时间】:2021-10-25 02:49:49
【问题描述】:
#include <mutex>
using namespace std;
int counter = 0;
mutex m;
void thread1() {
while(1) {
m.lock();
cout << "th1 " << counter << endl;
++counter;
if (counter == 300) {
m.unlock();
break;
}
m.unlock();
}
}
void thread2() {
while(1) {
m.lock();
cout << "th2 " << counter << endl;
if (counter == 10) {
counter = 300;
m.unlock();
break;
}
m.unlock();
}
}
int main(int argc, const char * argv[]) {
thread th1(thread1);
thread th2(thread2);
th1.join();
th2.join();
return 0;
}
我正在使用 while 循环运行两个线程。为什么尽管我使用 mutex lock 和 unlock 这段代码的结果每次都不同。
来自函数 thread1 的第一个代码被执行 X 次,然后来自函数 thread2 的代码被执行 y 次。
他们不应该一个接一个地执行吗.. thread1 -> thread2 -> thread1 -> 等等?
【问题讨论】:
-
我了解到您没有未定义的行为,而是已定义的行为:调度不确定。
-
测试“if (counter == 10)”可能永远不会变为真,因为 thread1 在重新调度 thread2 之前愉快地将 counter 增加到 10 以上。
-
我认为你对线程如何工作的想法是错误的。没有什么可以说线程 1 的循环会发生,然后线程 2 的循环会立即发生,它们会继续像那样交换。
-
操作系统调度线程的时序。
thread1可以在thread2计划运行之前轻松运行其循环的多次迭代,反之亦然。一旦它们都运行,操作系统将在自己选择的时间在线程之间交换。mutex只保证两个线程不能同时访问counter(或cout)。它对控制循环迭代的时间没有任何作用。 -
显然,如果您想在两个线程之间严格交替,编写单个循环(在单个线程中)会更简单高效。
标签: c++ multithreading while-loop mutex