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