我正在构建一个小型套接字服务器,我想在其中创建一个线程池,然后以老板- worker 线程模式工作。因此,每当主线程(boss)收到请求时,它就会被传递到池中的一个工作线程上。
在下面的代码片段中,我尝试创建 10 个线程。
void* process_data(void* arg) {
printf("invoked by the created thread");
while(1) {
// sleep until woken
// get item from queue
// do something
}
}
int total_threads_to_create = 10;
int total_created = 0;
while(total_created < 10) {
// create 10 threads
pthread_t thread;
int created = pthread_create(&thread, NULL, process_data, NULL);
if(created == 0) total_created++;
}
while(1) {
// server accepts the request in an infinite loop
int socket_fd = accept(ss_fd, (struct sockaddr*)&client_sock,&client_sock_len);
put_new_request_in_queue();
// signal to one of the thread that work is available
}
正如您在上面看到的,每个新线程都直接调用 process_data
方法。现在我希望 process_data
内的线程休眠,直到被主线程唤醒。
我该怎么办:
- 让
process_data
内的线程休眠直到被主线程唤醒? - 如何向工作线程发出信号,表明有请求需要处理?
最佳答案
正常的解决方案是条件变量和队列。这里的一般模式称为生产者/消费者模式。
您使用互斥体保护队列,然后使用条件变量来唤醒工作人员
制作人:
workToDo = generateSomeWork()
acquire mutex
queue.push(workToDo)
cv.notify();
release mutex
消费者:
loop:
acquire mutex
while queue empty
wait on cv (releasing mutex while waiting)
workToDo = queue.pop()
release mutex
do(workToDo)
就我个人而言,我还喜欢添加一个 bool 标志done
,当所有工作人员都需要清理时,该标志设置为 True。因此,当你想干净地退出程序时,你获取互斥体,将done设置为true,然后在cv上广播,这会唤醒所有的工作。他们看到 done
已设置,并干净地终止。
关于c - 如何通知工作线程有一些工作需要完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60024682/