如题所述:
编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
-----------------------------------------------------------------------------------------------------------------
用pthread_cond_signal,理论上会引起本该得到信号的线程一直处于饥饿状态,但我试过了,每次运行都ok。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <errno.h> pthread_cond_t cond_a; pthread_mutex_t mylock; int g_flag; #define NUM 3 void * func(void *arg) { int i; int name = (int)arg; printf("my name [%d]\n", name); for(i = 0; i<10;i++) { if( pthread_mutex_lock(&mylock)) { printf("pthread_mutex_lock error errmsg[%s]\n", strerror(errno)); exit(0); } while(1) { if(g_flag == name) { g_flag = (g_flag+1)%NUM; printf("%c ", ‘A‘ + name); break; } else { if(pthread_cond_wait(&cond_a, &mylock)) { printf("wait error errmsg[%s]\n", strerror(errno)); exit(0); } } } if(pthread_mutex_unlock(&mylock)) { printf("pthread_mutex_unlock error errmsg[%s]\n", strerror(errno)); exit(0); } //if(pthread_cond_broadcast(&cond_a)) if(pthread_cond_signal(&cond_a)) { printf("pthread_cond_broadcast error errmsg[%s]\n", strerror(errno)); exit(0); } } printf("\n"); pthread_exit(NULL); } int appInit() { g_flag = 0; pthread_mutex_init(&mylock, NULL); pthread_cond_init(&cond_a, NULL); return 0; } int appDone() { pthread_cond_destroy(&cond_a); pthread_mutex_destroy(&mylock); return 0; } int main(int argc, char *argv[]) { pthread_t th[NUM]; int ret; int i; ret = appInit(); if(ret) { printf("appinit failure\n"); return -1; } for( i = 0; i < NUM; i++) { ret = pthread_create(&th[i], NULL, func, (void*)i); if(ret) { printf("pthread_create ta error [%s]\n", strerror(errno)); return 1; } } for( i = 0; i < NUM; i++) pthread_join(th[i], NULL); printf("main thread exit\n"); ret = appDone(); if(ret) { printf("appDone failure\n"); return -1; } return 0; }
时间: 2024-09-28 05:16:15