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