【发布时间】:2020-05-18 08:24:46
【问题描述】:
我正在构建一个小型套接字服务器,我想在其中创建一个线程池,然后以 boss-worker 线程模式工作。因此,每当主(老板)收到请求时,它就会从池中传递到其中一个工作线程。
在下面的sn-p中,我尝试创建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中的线程休眠直到被主线程唤醒? - 我如何向工作线程发出信号表明有请求得到处理?
【问题讨论】:
-
条件变量?
-
@Shawn 你能举个例子吗?我读过它们,但不确定如何在这种情况下使用它们。
标签: c multithreading sockets pthreads