写的不成功,各位有更好的方法请留言
// https://blog.csdn.net/c_base_jin/article/details/89741247
#include <Windows.h>
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
std::mutex mtx,mut;
std::condition_variable cv;
bool ready = false;
int g_data[5]= { 0,1,2,3,4 };
using namespace std;
constexpr auto N = 5;
int now = 0;
void go() {
//unique_lock<std::mutex> lck(mtx);
ready = true;
cv.notify_all(); // 这是重点
}
void f(int m_id) {
int m_last;
int m_data[5];
if (m_id == 0)m_last = N - 1;
else m_last = m_id - 1;
cout << "启动 " << m_id << endl;
for (int i = 1; i < N; ) {
std::unique_lock<std::mutex> lck(mtx);
while(!ready)cv.wait(lck);
//ready = false;
if (now == m_id) {
cout << m_id << "号线程第" << i << "次接受信息" << endl;
i++;
mut.lock();
now++;
mut.unlock();
std::copy(std::begin(g_data), std::end(g_data), std::begin(m_data));
if (now == N) {
mut.lock();
now = 0;
mut.unlock();
}
std::copy(std::begin(m_data), std::end(m_data), std::begin(g_data));
Sleep(300);
ready = false;
go();
}
}
cout << m_id << "号线程结束" << endl;
return;
}
std::thread threads[N+1];
int main()
{
for (int i = 0; i < N; i++) {
threads[i] = std::thread(f, i);
}
cout << "线程设置完成,开始:" << endl;
go();
for (int i = 0; i < N; i++) {
threads[i].join();
}
return 0;
}