C++ 异步线程池继续执行而不阻塞
我有一个线程池,其中每个线程都必须是一个等待线程,并不断侦听新任务以异步处理它们(处理过程需要很长时间)。但是,在下面的代码中,我无法获得这种行为。问题是,当我创建线程池时,它们成功地执行了给定的第一个任务。process()函数到达deC++ 异步线程池继续执行而不阻塞,c++,multithreading,asynchronous,C++,Multithreading,Asynchronous,我有一个线程池,其中每个线程都必须是一个等待线程,并不断侦听新任务以异步处理它们(处理过程需要很长时间)。但是,在下面的代码中,我无法获得这种行为。问题是,当我创建线程池时,它们成功地执行了给定的第一个任务。process()函数到达de返回0当线程正在计算任务时,但它永远不会返回main()。它位于v.wait(l,[&]{return!tasks.empty();})中行,也就是说,它仍然等待新任务被推送到任务队列中,而这永远不会发生。我已经读到它与std::future析构函数有关:如果我
返回0代码>当线程正在计算任务时,但它永远不会返回main()。它位于v.wait(l,[&]{return!tasks.empty();})中代码>行,也就是说,它仍然等待新任务被推送到任务队列中,而这永远不会发生。我已经读到它与std::future析构函数有关:如果我没有错的话,我认为当process()到达返回时,将调用std::future析构函数,它将等待所有线程结束,但它们永远不会结束
代码如下:
static int callings = 0;
class ThreadPool
{
private:
std::queue<int> tasks;
std::mutex m;
std::vector<std::future<void>> finished;
std::condition_variable v;
public:
void push_task(int arg) {
std::unique_lock<std::mutex> l(m);
tasks.push(arg);
v.notify_one(); // wake a thread to work on the task
}
void read_tasks() {
while (true) {
std::unique_lock<std::mutex> l(m);
if (tasks.empty()) {
//waits till new task
v.wait(l, [&] {return !tasks.empty(); }); //after completing the first task, the program stays here forever
}
int task = tasks.front(); // read task
tasks.pop(); //delete task
//run the task
std::this_thread::sleep_for(std::chrono::milliseconds(5 * 1000)); //simulate computation
}//while true
}
void create_thread_pool(int m_threads_count) {
for (int t_i = 0; t_i < m_threads_count; t_i++) {
finished.push_back(std::async(std::launch::async,[this] { read_tasks(); }));
printf("Thread %d is doing work...\n", t_i);
}
}
}; //ThreadPool
int process(){
ThreadPool pool;
if(callings == 0)
{
pool.create_thread_pool(4);
}
//give some task to do...
pool.push_task(callings);
callings++;
return 0; //point reached but never returning to main
}
int main(){
while(true){
// do things...
process();
// do more things...
// this does not execute, how to solve this?
}
return 0;
}
static int callings=0;
类线程池
{
私人:
std::队列任务;
std::互斥m;
std::向量完成;
std::条件变量v;
公众:
无效推送任务(int参数){
std::唯一锁l(m);
任务推送(arg);
v、 notify_one();//唤醒线程以处理任务
}
无效读取任务(){
while(true){
std::唯一锁l(m);
if(tasks.empty()){
//等待新任务
v、 wait(l,[&]{return!tasks.empty();});//完成第一个任务后,程序将永远留在这里
}
int task=tasks.front();//读取任务
tasks.pop();//删除任务
//运行任务
std::this_thread::sleep_for(std::chrono::毫秒(5*1000));//模拟计算
}//虽然是真的
}
无效创建线程池(整数m线程数){
对于(int t_i=0;t_i
当线程一直等待新任务而不阻塞时,如何返回main()
提前感谢std::async
创建了一个线程,该线程的返回值需要在某个点进行同步。您需要的是更原始的-只需尝试使用std::thread
。这会生成一个不包含同步的线程。您是否意识到在退出进程后销毁了线程池
?您应该将其移动到main
并将引用/指针传递到process