gpt4 book ai didi

c++ - C++ 11多线程生产者/消费者程序挂起

转载 作者:行者123 更新时间:2023-12-03 13:22:50 28 4
gpt4 key购买 nike

我是C++ 11的新手,并使用线程功能。在以下程序中,主线程启动9个工作线程,并将数据插入队列,然后等待线程终止。我看到工作线程没有被唤醒,程序只是挂起了。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <vector>
#include <chrono>
#include <future>
#include <atomic>
using namespace std::chrono_literals;

std::mutex _rmtx;
std::mutex _wmtx;
std::queue<unsigned long long> dataq;
std::condition_variable _rcv;
std::condition_variable _wcv;
std::atomic_bool termthd;

void thdfunc(const int& num)
{
std::cout << "starting thread#" << num << std::endl;

std::unique_lock<std::mutex> rul(_rmtx);
while (true) {
while(!_rcv.wait_until(rul, std::chrono::steady_clock::now() + 10ms, [] {return !dataq.empty() || termthd.load(); }));
if (termthd.load()) {
std::terminate();
}
std::cout<<"thd#" << num << " : " << dataq.front() <<std::endl;
dataq.pop();
_wcv.notify_one();
}
}

int main()
{
std::vector<std::thread*> thdvec;
std::unique_lock<std::mutex> wul(_rmtx);
unsigned long long data = 0ULL;
termthd.store(false);
for (int i = 0; i < 9; i++) {
thdvec.push_back(new std::thread(thdfunc, i));
}

for ( data = 0ULL; data < 2ULL; data++) {
_wcv.wait_until(wul, std::chrono::steady_clock::now() + 10ms, [&] {return data > 1000000ULL; });
dataq.push(std::ref(data));
_rcv.notify_one();
}
termthd.store(true);
_rcv.notify_all();
//std::this_thread::yield();
for (int i = 0; i < 9; i++) {
thdvec[i]->join();
}
}
我无法找出问题所在。如何确保线程被唤醒并处理请求并正常终止?

最佳答案

std::unique_lock<std::mutex> wul(_rmtx);将锁定_rmtx互斥锁,直到主作用域结束。这肯定是一个问题,因为其他试图锁定_rmtx的线程将阻塞:

int main()
{
std::vector<std::thread*> thdvec;
std::unique_lock<std::mutex> wul(_rmtx); // <- locking mutex until end of main.
// other threads trying to lock _rmtx will block

unsigned long long data = 0ULL;
// ... rest of the code ...

关于c++ - C++ 11多线程生产者/消费者程序挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66004890/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com