#include #include #include #include #include #include static pthread_t worker1_thr; static pthread_t worker2_thr; static pthread_mutex_t worker_mtx; static pthread_cond_t worker_go; static pthread_cond_t worker_done; struct workitem { struct workitem *next; int a, b; }; struct workitem *head; static void * worker(void *arg) { struct workitem *w; pthread_detach(pthread_self()); fprintf(stderr, "WORKER: started %p\n", arg); pthread_mutex_lock(&worker_mtx); for (;;) { while (head == NULL) { pthread_cond_wait(&worker_go, &worker_mtx); } while (w = head) { head = w->next; fprintf(stderr, "WORKER: got work a=%d b=%d\n", w->a, w->b); free(w); pthread_cond_signal(&worker_done); } } } void work_add(int a, int b) { struct workitem *w; int dowake = 0; w = calloc(sizeof(*w), 1); w->a = a; w->b = b; pthread_mutex_lock(&worker_mtx); if (head == 0) dowake = 1; w->next = head; head = w; if (dowake) pthread_cond_signal(&worker_go); pthread_mutex_unlock(&worker_mtx); } int main() { pthread_mutex_init(&worker_mtx, NULL); pthread_cond_init(&worker_go, NULL); pthread_cond_init(&worker_done, NULL); fprintf(stderr, "pthread create\n"); pthread_create(&worker1_thr, NULL, worker, (void *)1); pthread_create(&worker2_thr, NULL, worker, (void *)2); work_add(10, 15); work_add(11, 22); work_add(314, 159); pthread_mutex_lock(&worker_mtx); while (head != NULL) { pthread_cond_wait(&worker_done, &worker_mtx); } pthread_mutex_unlock(&worker_mtx); fprintf(stderr, "job complete\n"); exit(0); }