java 限制线程数量_限制并发线程的数量(使用pthreads)

这篇博客探讨了如何在程序启动时创建一个固定大小的线程池,以提高效率。作者建议使用结构体来表示工作线程,并通过条件变量和互斥锁进行同步。每个线程都有一个唯一ID,完成任务后将其ID添加到管理器的列表中,由管理器读取结果并重新分配任务。这种方法避免了频繁的线程创建和销毁,提高了系统的响应速度。
摘要由CSDN通过智能技术生成

而不是按需创建/销毁线程,在启动时创建10个工作线程池并让主程序向它们提供作业会更容易 .

在启动时,您将创建一个包含10个工作程序的数组 . 这些可能看起来像

typedef struct worker

{

pthread_t thread;

pthread_cond_t cond;

pthread_mutex_t mutex;

struct job* job;

int quit;

} worker;

管理员将通过设置他们的 job 成员然后向工作人员发送信号来依次将作业委托给每个线程 .

每个工作人员都会循环,直到 quit 非零,等待其状态发出信号 . 在每个信号之后,它会在报告结果之前读取/处理其 job ,然后再次等待其条件 .

Edit: 这里的're not keen on thread pools. You could instead try giving each thread a unique id; store some mapping between ids and other properties of each thread in the manager. When each thread completes, have it add its id to a list owned by the manager then signal a condition in the manager. Each time the manager wakes, it can pull the head from the list, lookup the appropriate thread, read back its job results then join the thread. Note that the manager'列表将被多个线程访问,因此读/写需要由互斥锁保护 .

Edit2: 你'd like to know more about conditions and don't找到你的例子've found helpful. I'我不确定这个'll be any better but here' s some code I've written . OsSemaphore* 函数将条件包装到一个简单的Wait / Signal API中 .

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值