你想是這樣的:
struct thread_data {
int stop;
pthread_cond_t * flag;
pthread_mutex_t * lock;
int * failCount;
int * successCount;
};
void * foobar(void * ptr)
{
struct thread_data * data = (struct thread_data*)ptr;
int fail = 0;
while (isWorkToBeDone() && !data->stop) {
// do some work
if (encounteredError()) {
pthread_mutex_lock(data->lock);
data->failCount += 1;
fail = 1;
pthread_cond_signal(data->flag);
pthread_mutex_unlock(data->lock);
}
}
// clean up
if (!fail) {
pthread_mutex_lock(data->lock);
data->successCount += 1;
pthread_cond_signal(data->flag);
pthread_mutex_unlock(data->lock);
}
pthread_exit(NULL);
}
int runThreads()
{
pthread_t * threads;
pthread_mutex_t lock;
pthread_cond_t flag;
int i;
struct thread_data data;
threads = malloc(sizeof(*threads)*numThreads);
if (!threads) {
// handle malloc error
return 0;
}
// initialize mutex and condition variable
pthread_mutex_init(&lock, NULL);
pthread_cond_init(&flag, NULL);
data.stop = 0;
data.flag = &flag;
data.lock = &lock;
data.failCount = 0;
data.successCount = 0;
for (i = 0; i < numThreads; ++i) {
if (!pthread_create(threads+i, NULL, foobar,
(void *)(threads+i))) {
// handle thread creation error
}
}
while (!data.stop) {
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
// a thread just finished
if (data.failCount > 0) {
data.stop = 1;
} else if (data.successCount == numThreads) {
data.stop = 1;
}
pthread_mutex_unlock(&lock);
}
for (i = 0; i < numThreads; ++i) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&flag);
free(threads);
}
它的工作方式是你等任何一個線程失敗,或所有線程成功,然後讓所有線程知道停止工作並通過stop
變量乾淨地退出。
而不是讓線程檢查stop
變量,你可以調用pthread_kill()
,但它更好地乾淨地退出每個線程。