Sleep()和yiled()函数

 

 

#include<iostream>
#include<thread>
#include<mutex>
#include<atomic>
using namespace std;
mutex g_mutex;
atomic<bool> isok = false;
void func(int id) {

    //只有当所有线程创建完成之后才能启动,否则会被挂起,让出cpu的控制权给其它等待的线程使用
    while (isok == false) {
        this_thread::yield();
    }

    for (int i = 0; i < 5; i++) {
        lock_guard<mutex> lock(g_mutex);
        cout << "thread id=" << id << "    " << i << endl;
    }
}

int main()
{
    thread threads[5];

    for (int i = 0; i < 5; i++) {
        threads[i] = thread(func, i);
    }
    isok = true;
    
    for (int i = 0; i < 5; i++) {
        threads[i].join();
    }
    system("pause");
    return 0;
}

 

posted @ 2020-05-28 18:55  知道了呀~  阅读(267)  评论(0编辑  收藏  举报