原文地址: http://www.linuxquestions.org/questions/programming-9/how-to-implement-waitformultipleobjects-in-linux-908553/
#include <stdlib.h> #include <stdio.h> #include <semaphore.h> #include <pthread.h> #include <unistd.h> #include <errno.h> #include <string.h> #define NUM_THREADS (2) sem_t semaphore; void *worker_thread(void *arg) { int i; for (i=0; i<10; ++i) { fprintf(stderr,"."); sleep(1); } sem_post(&semaphore); return NULL; } int main(int argc, char* argv[]) { pthread_t thread[NUM_THREADS]; int i; sem_init(&semaphore, 0, -1 * NUM_THREADS); for (i =0; i< NUM_THREADS; ++i) { pthread_create(&thread[i],NULL, &worker_thread, NULL); } if (sem_wait(&semaphore) < 0) { printf("sem_wait failed: %s\n", strerror(errno)); return EXIT_FAILURE; } for (i =0; i< NUM_THREADS; ++i) { pthread_join(thread[i], NULL); } printf("\nAll threads are done now\n"); return EXIT_SUCCESS; }