【发布时间】:2015-11-03 23:13:16
【问题描述】:
假设我在while 循环中使用pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*fun) (void *), void *arg),一旦它完成函数fun(),线程会发生什么,如果我调用int pthread_detach(pthread_t thread),它是否也会落入主线程的循环中?还是只有主线程留在循环中?
例子:
pthread_t t[NTHREADS];
int i = -1;
while(1){
//do something
++i;
pthread_create(&t[i], NULL, fun, (void *)i);
pthread_detach(t[i]);
//main thread goes on, created one detaches when finished
}
我想要做的是一个多客户端服务器,其中每个线程为其自己的客户端提供服务,有 NTHREADS 并且当某个线程完成 fun() 或者更确切地说为它的客户端提供服务时,t[] 中的插槽打开并如果之前已满,可以创建另一个线程(其他客户端可以连接)。
【问题讨论】:
-
您需要一个互斥锁来保护
t,以便线程可以在返回之前安全地将t[i]设置为“未使用”值。
标签: c multithreading pthreads