#include #include #include #include struct element { int value; struct element *next; } *head = NULL, *tail = NULL; void add_element(int v) { struct element *e = malloc(sizeof(struct element)); e->next = NULL; e->value = v; if (tail == NULL) head = tail = e; else tail = tail->next = e; } int take_element() { int v = head->value; struct element *e = head; head = head->next; if (head == NULL) tail = NULL; free(e); return v; } #define DO_HEAVY_COMPUTATION (usleep(rand() % 10000000), rand() % 1000000) void *worker_thread(void *arg) { srand(time(0) + (intptr_t)arg); while (1) { int v = DO_HEAVY_COMPUTATION; pthread_testcancel(); add_element(v); } } int main() { pthread_t t[4]; for (int i = 0; i < 4; ++i) pthread_create(t + i, NULL, worker_thread, NULL); int computed_count = 0; while (computed_count < 10) { while (head == NULL); int value = take_element(); printf("%02d: %d\n", ++computed_count, value); } for (int i = 0; i < 4; ++i) pthread_cancel(t[i]); for (int i = 0; i < 4; ++i) pthread_join(t[i], NULL); return 0; }