三个线程按顺序打印ABC

首先思路是一个线程在工作时,需要阻塞另外两个线程,这样需要三个线程共用一个互斥锁,但问题是怎样指定顺序呢。

想到的办法是通过一个全局变量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,所以未做处理。

效果如下图

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章