我正在寫一個多線程控制檯應用程序使用WinAPI的關鍵部分作爲同步機制。我需要創建5個線程,每個線程都有自己的字符串以供線程顯示。線程應該逐個輸出它們的字符串。如何強制線程按嚴格順序工作?
所以,我有線程函數:
void thread_routine(void* data)
{
std::string* st = (std::string*)data;
while(1)
{
/* enter critical section */
std::cout << st; // not exactly that way, but I hope that you understood what I've meant.
Sleep(100);
/* leave critical section */
}
}
在我main()
for(int i = 0; i < 10; ++i)
_beginthread(thread_routine, 0, strings[i]);
嗯,我希望看到類似[01]:
1) First thread
2) Second thread
3) Third thread
4) Fourth thread
5) Fifth thread
... and so on
但不是這個輸出,我看到了像[O]:
1) First thread
1) First thread
3) Third thread
2) Second thread
5) Fifth thread
... and so on
我清楚地明白髮生了什麼:這些線程通過關鍵部分的順序是未知的,所以部分將通過一個隨機捕捉,但我需要我的同步線程來獲得輸出,如[o1]。那我該怎麼做?有沒有任何模式?
不要將I/O置於關鍵部分。在線程完成後進行打印*。 –
@KerrekSB如何在不將IO放入關鍵部分的情況下實現順序輸出? – Netherwire
線程的目的不是分離出某些不依賴於特定執行順序的計算步驟。如果你想擁有s.th.在有序執行中使用同步對象,如互斥鎖和信號量! –