如何使用带有 pthreads 的线程池?

编程入门 行业动态 更新时间:2024-10-27 23:20:47
本文介绍了如何使用带有 pthreads 的线程池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个作业队列,我想创建一个包含四个线程的池,我可以在其中投放我的作业.我所困扰的是如何制作线程并在没有工作时保持它们暂停.

I have a queue of jobs and I want to make a pool of four threads where I can throw my jobs at. What I am stuck at is in how to make the threads and keep them suspended while there is no work.

JOB QUEUE | job1 | job2 | job3 | job4 | .. THREAD POOL | thread1 | thread2 | thread3 | thread4 |

要创建我目前在初始化点拥有的线程:

To create the threads I have currently at the initialisation point:

for (t=0; t<num_of_threads; t++){ pthread_create(&(threads[t]), NULL, doSth2, NULL); }

其中 num_of_threads=4 和 doSth2 是一个内部没有任何内容的函数.因此,一旦我创建了 4 个线程并使用 doSth2 完成了它们,我该如何在不杀死它们的情况下为它们提供新的工作?

Where num_of_threads=4 and doSth2 is a function with nothing inside. So once I have created the 4 threads and they are done with doSth2, how can I give them new work to do, without killing them?

推荐答案

线程池的关键是队列.这是我开发的线程池的修改函数.

The key to a thread pool is a queue. Here are modified functions for a thread pool I have developed.

void queue_add(queue q, void *value) { pthread_mutex_lock(&q->mtx); /* Add element normally. */ pthread_mutex_unlock(&q->mtx); /* Signal waiting threads. */ pthread_cond_signal(&q->cond); }

从队列中获取元素

void queue_get(queue q, void **val_r) { pthread_mutex_lock(&q->mtx); /* Wait for element to become available. */ while (empty(q)) rc = pthread_cond_wait(&q->cond, &q->mtx); /* We have an element. Pop it normally and return it in val_r. */ pthread_mutex_unlock(&q->mtx); }

更多推荐

如何使用带有 pthreads 的线程池?

本文发布于:2023-08-04 22:57:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1300343.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   如何使用   pthreads

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!