使用条件变量控制三个线程输出数据,
第一个线程输出3的倍数余1,
第二个线程输出3的倍数余2,
第三个线程输出3的倍数
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex g_mutex;
condition_variable g_conV;
void thread_1_func(int& i);
void thread_2_func(int& i);
void thread_3_func(int& i);
int main()
{
int i = 1;
thread thread_1(thread_1_func, ref(i));
thread thread_2(thread_2_func, ref(i));
thread thread_3(thread_3_func, ref(i));
thread_1.join();
thread_2.join();
thread_3.join();
}
void thread_1_func(int& i)
{
while (true)
{
// 这个线程运行一次
cout << "thread_1 running ..." << i << endl;
unique_lock<mutex> lock(g_mutex);
g_conV.wait(lock, [&i]() {return i % 3 == 1; }); // 当某个i处于99 的时候,这个肯定处于wait状态,wait的那个线程会输出100
cout << "thread_1 " << i << endl;
i++;
if (i > 100) return; // 达到100之后,就不用notify了,不用通知其他的县线程了
g_conV.notify_one();
}
}
void thread_2_func(int& i)
{
while (true)
{
// 这个线程运行一次
cout << "thread_2 running ..." << i << endl;
unique_lock<mutex> lock(g_mutex);
g_conV.wait(lock, [&i]() {return i % 3 == 2; }); // 当某个i处于99 的时候,这个肯定处于wait状态,wait的那个线程会输出100
cout << "thread_2 " << i << endl;
i++;
if (i > 100) return; // 达到100之后,就不用notify了,不用通知其他的县线程了
g_conV.notify_one();
}
}
void thread_3_func(int& i)
{
while (true)
{
// 这个线程运行一次
cout << "thread_3 running ..." << i << endl;
unique_lock<mutex> lock(g_mutex);
g_conV.wait(lock, [&i]() {return i % 3 == 0; }); // 当某个i处于99 的时候,这个肯定处于wait状态,wait的那个线程会输出100
cout << "thread_3 " << i << endl;
i++;
if (i > 100) return; // 达到100之后,就不用notify了,不用通知其他的县线程了
g_conV.notify_one();
}
}
条件变量中的notifyOne和notifyAll是线程间通信的方法。
notifyOne是唤醒等待在该条件变量上的一个线程。如果有多个线程在该条件变量上等待,那么只会唤醒其中一个线程。具体哪个线程被唤醒是由操作系统决定的。
notifyAll是唤醒等待在该条件变量上的所有线程。如果有多个线程在该条件变量上等待,那么所有线程都会被唤醒。
notifyOne和notifyAll的使用场景取决于具体的需求。当只需要唤醒一个线程时,可以使用notifyOne。而当需要唤醒所有等待的线程时,可以使用notifyAll。