编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
方法1:使用信号量semaphore
#include <stdio.h> #include <stdlib.h> #include <semaphore.h> #include <unistd.h> #include <pthread.h> sem_t g_sem; int count = 0; void *thread_fun1(void *arg) { while(1) { if(count == 10) { break; } sem_wait(&g_sem); printf("thread1's id is %d\n", pthread_self()); sem_post(&g_sem); sleep(1); } return (void*)0; } void *thread_fun2(void* arg) { while(1) { if(count == 10) { break; } sem_wait(&g_sem); printf("thread2's id is %d\n", pthread_self()); sem_post(&g_sem); sleep(1); } return (void*)0; } void *thread_fun3(void *arg) { while(1) { sem_wait(&g_sem); printf("thread3's id is %d\n\n", pthread_self()); sem_post(&g_sem); if(++count == 10) { break; } sleep(1); } return (void*) 0; } int main() { pthread_t thread1; pthread_t thread2; pthread_t thread3; int res = 0; res = sem_init(&g_sem,0,0); if(res) { printf("Semaphore initilization failed\n"); return -1; } res = pthread_create(&thread1, NULL, thread_fun1, NULL); if(res) { printf("Thread1 created failed\n"); } res = pthread_create(&thread2, NULL, thread_fun2, NULL); if(res) { printf("thread2 created fialed\n"); } res = pthread_create(&thread3, NULL, thread_fun3, NULL); if(res) { printf("thread3 created failed\n"); } sem_post(&g_sem); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); }
方法2:使用互斥变量mutex
#include <stdio.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t g_mutex; int count = 0; int num_count = 0; void *thread_fun1(void* arg) { while(1) { if(count % 3 == 0) { pthread_mutex_lock(&g_mutex); count++; printf("thread1's id is %d\n",pthread_self()); pthread_mutex_unlock(&g_mutex); } if(num_count == 10) break; } return (void*) 0; } void* thread_fun2(void* arg) { while(1) { if(count %3 == 1) { pthread_mutex_lock(&g_mutex); count++; printf("thread2's id is %d\n",pthread_self()); pthread_mutex_unlock(&g_mutex); } if(num_count == 10) break; } return (void*) 0; } void* thread_fun3(void* arg) { while(1) { if(count %3 == 2) { pthread_mutex_lock(&g_mutex); count++; printf("thread3's id is %d\n\n", pthread_self()); num_count ++; pthread_mutex_unlock(&g_mutex); } if(num_count == 10) break; } return (void*) 0; } int main() { pthread_t thread1, thread2, thread3; int res = 0; pthread_mutex_init(&g_mutex, NULL); res = pthread_create(&thread1, NULL, thread_fun1, NULL); if(res) { printf("trhead1 created failed\n"); } res = pthread_create(&thread2, NULL, thread_fun2, NULL); if(res) { printf("thread2 created faield\n"); } res = pthread_create(&thread3, NULL, thread_fun3, NULL); if(res) { printf("thread3 cerated failed\n"); } pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); }