一种方法(即假设线程实际完成,其他可能的陷阱之中我还没有了解还)是使用一个互斥体,或东西沿着线:
#include <err.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <unistd.h>
pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t Job_Done = PTHREAD_COND_INITIALIZER;
unsigned long Threads_Completed;
void *worker(void *unused);
int main(void)
{
pthread_t *tids;
struct timespec wait;
if ((tids = calloc(sizeof(pthread_t), 42)) == NULL)
err(EX_OSERR, "could not calloc() threads list");
fprintf(stderr, "dbg starting...\n");
for (unsigned int i = 0; i < 42; i++) {
if (pthread_create(&tids[i], NULL, worker, NULL) != 0)
err(EX_OSERR, "could not pthread_create() thread %u", i);
}
wait.tv_sec = 7;
wait.tv_nsec = 0;
for (;;) {
pthread_mutex_lock(&Lock);
if (Threads_Completed == 42)
break;
pthread_cond_timedwait(&Job_Done, &Lock, &wait);
pthread_mutex_unlock(&Lock);
}
fprintf(stderr, "dbg all done!\n");
exit(EXIT_SUCCESS);
}
void *worker(void *unused)
{
sleep(3 + rand() % 7); // actual work here
fprintf(stderr, "dbg done!\n");
pthread_mutex_lock(&Lock);
Threads_Completed++;
pthread_mutex_unlock(&Lock);
pthread_cond_signal(&Job_Done);
return (void *) 0;
}
你叫pthread_detach( tid)或使用pthread_attr_setdetachedstate()以分离状态创建线程? –
不,我不知道他们,我没有给他们打电话。我应该发布源代码吗? –
是的,发布代码会很有帮助 - 谢谢。 –