C++ 3个线程顺序输出1-9

3个线程,顺序输出123456789

#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int g_num = 0;
mutex myMutex;
condition_variable cv1, cv2, cv3;

void thread_Func1()
{
    int a = 0;
    while (true)
    {
        a = -1;
        {
            unique_lock  guard(myMutex);
            {
                while (a % 3 != 1 || a == - 1)
                {
                    cv1.wait(guard);
                    a = g_num;
                }
            }
        }
        cout << " thread_id : " << std::this_thread::get_id() << " g_numer : " <<  a << endl;
        if (a == 7)
            break;
    }
}

void thread_Func2()
{
    int a = -1;
    while (true)
    {
        a = -1;
        {
            unique_lock  guard(myMutex);
            {
                while (a % 3 != 2 || a == -1)
                {
                    cv2.wait(guard);
                    a = g_num;
                }
            }
        }
        cout << " thread_id : " << std::this_thread::get_id() << " g_numer : " << a << endl;
        if (a == 8)
            break;
    }
}


void thread_Func3()
{
    int a = 0;
    while (true)
    {
        a = -1;
        {
            unique_lock  guard(myMutex);
            {
                while (a % 3 != 0 || a == -1 )
                {
                    cv3.wait(guard);
                    a = g_num;
                }
            }
        }
        cout << " thread_id : " << std::this_thread::get_id() <<  " g_numer : " << a << endl;
        if (a == 9)
            break;
    }
}
void thread_ctl()
{
    int a = 0;
    while (a < 9)
    {
        {
            unique_lock  guard(myMutex);
            a = ++g_num;
        }
        if (a % 3 == 1)
            cv1.notify_one();
        else if (a % 3 == 2)
            cv2.notify_one();
        else
            cv3.notify_one();
        Sleep(1000);
    }
}

int main()
{
    std::thread threadFunc1(thread_Func1);
    std::thread threadFunc2(thread_Func2);
    std::thread threadFunc3(thread_Func3);

    std::thread threadCtl(thread_ctl);

    threadFunc1.join();
    threadFunc2.join();
    threadFunc3.join();

    threadCtl.join();
    return 0;
}

C++ 3个线程顺序输出1-9_第1张图片

你可能感兴趣的:(C++ 3个线程顺序输出1-9)