#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx; // 全局互斥锁.
std::condition_variable cv; // 全局条件变量.
bool ready = false; // 全局标志位.
//1.当一个线程进入时会上锁,然后调用wait会使线程阻塞,然后会解锁
//2.当解锁之后其他线程就可以获得锁,所以所有的线程都会阻塞
//3.notify的时候wait会上锁
//看来这锁和wait操作一起使用可以很好的保证线程的安全,在notif之前能保证只有一个线程访问,在notif之后也能保证只有一个线程访问
void do_print_id(int id)
{
std::unique_lock <std::mutex> lck(mtx);
while (!ready)
cv.wait(lck);
std::cout << "thread " << id << '\n';
}
void go()
{
std::unique_lock <std::mutex> lck(mtx);
ready = true; // 设置全局标志位为 true.
cv.notify_all(); // 唤醒所有线程.
}
int main()
{
std::thread threads[10];
// spawn 10 threads:
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(do_print_id, i);
std::cout << "10 threads ready to race...\n";
go(); // go!
for (auto & th:threads)
th.join();
getchar();
return 0;
}