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

而不是按需创建/销毁线程,在启动时创建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中 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值