首先思路是一個線程在工作時,需要阻塞另外兩個線程,這樣需要三個線程共用一個互斥鎖,但問題是怎樣指定順序呢。
想到的辦法是通過一個全局變量nFlag,以此判斷下一個應該打印哪一個字母。
但是如何指定呢,比如A打印完成後,nFlag指定B,而C線程繼續等待。
可以在進入互斥鎖前設定一個死循環,沒有輪到的字母一直阻塞在這裏,而輪到的線程進入工作狀態。
所以代碼如下
// InOrderABCThread.cpp : 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include <thread>
#include <string>
#include <iostream>
#include <mutex>
#include <map>
std::mutex g_mutexPrint;
std::mutex g_mutexMap;
int nFlag = 0;
std::map<std::string, int> g_mapList;
// 三個線程按順序打印abc
void PrintABC(std::string strX)
{
auto itrFlag = g_mapList.find(strX);
for (int i = 0; i < 10; ++i)
{
{
while (itrFlag->second != nFlag)
{
}
}
std::lock_guard<std::mutex> guardPrint(g_mutexPrint);
std::cout << strX << " ";
if (nFlag == 2)
{
nFlag = 0;
}
else
{
nFlag++;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
g_mapList.insert(std::make_pair("A", 0));
g_mapList.insert(std::make_pair("B", 1));
g_mapList.insert(std::make_pair("C", 2));
std::thread th1(PrintABC, "A");
std::thread th2(PrintABC, "B");
std::thread th3(PrintABC, "C");
th1.join();
th2.join();
th3.join();
system("pause");
return 0;
}
代碼中默認第一個進入的是A,所以未做處理。
效果如下圖