1
我正在学习C++中的多线程并刚刚发现互斥锁。我的代码如下:C++意外的多线程行为
#include "stdafx.h"
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
using namespace std;
std::mutex mu;
void shared_print(string msg, int i) {
std::lock_guard<std::mutex> guard(mu);
cout << msg << i << endl;
}
void function_1() {
for (int i = 0; i > -3; i--)
shared_print("Thread1: ", i);
}
int main() {
std::thread thread1(function_1);
for (int i = 0; i < 3; i++)
shared_print("Main: ", i);
thread1.join();
return 0;
}
从我的理解中,互斥锁一次只允许访问一个资源。所以互斥量将被第一个调用它的线程锁定(Thread1
)。当main
线程尝试访问互斥锁时,它将被阻止,直到互斥锁被解锁为Thread1
。一旦cout
执行后,它将被解除阻塞,其中main
将被允许执行。
我希望得到的结果进行交错的呼叫如Thread1, Main, Thread1, Main
等
然而,而是我得到标准输出下面的结果。该模式仍然是任何迭代次数相同:
Thread1: 0
Thread1: -1
Thread1: -2
Main: 0
Main: 1
Main: 2
为什么它会交错?没有您的代码强制执行的命令。如果一个线程仍然有CPU时间,它可以获得刚刚释放的锁。 – Arash