ที่นี่เราจะดูการพิมพ์ตัวเลขเรียงลำดับด้วย threads หลายตัว สร้าง n threads แล้ว synchronize thread แรกพิมพ์ 1 thread ที่สองพิมพ์ 2 ตามลำดับ เมื่อ thread หนึ่งพิมพ์ จะ lock resource ไม่ให้ thread อื่นใช้
ตัวอย่างโค้ด
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t* cond = NULL; int threads; volatile int count = 0; void* sync_thread(void* num) { int thread_number = *(int*)num; while(1) { pthread_mutex_lock(&mutex); if(thread_number != count) { pthread_cond_wait(&cond[thread_number], &mutex); } printf("%d ", thread_number + 1); count = (count+1)%(threads); pthread_cond_signal(&cond[count]); pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t* thread_id; volatile int i; int* thread_arr; printf("\nEnter number of threads: "); scanf("%d", &threads); cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t) * threads); thread_id = (pthread_t*)malloc(sizeof(pthread_t) * threads); thread_arr = (int*)malloc(sizeof(int) * threads); for(i = 0; i < threads; i++) { thread_arr[i] = i; pthread_create(&thread_id[i], NULL, sync_thread, (void*)&thread_arr[i]); } for(i = 0; i < threads; i++) { pthread_join(thread_id[i], NULL); } return 0; }ผลลัพธ์
$ g++ test.cpp -lpthread $ ./a.out Enter number of threads: 5 1 2 3 4 5 1 2 3 4 5 ... (วนซ้ำ)