有四个线程1、2、3、4。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:
A:1 2 3 4 1 2....
B:2 3 4 1 2 3....
C:3 4 1 2 3 4....
D:4 1 2 3 4 1....
题目意思是使线程有序执行
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <string.h> int nThread=0; int nThreadOrder[4]={2,0,1,3}; char strThread[4]={'1','2','3','4'}; pthread_mutex_t pMutex; pthread_cond_t pCond; void * threadFun(void *argv) { int numTemp=(int)argv; int i=0; for(;i<10;i++) { pthread_mutex_lock(&pMutex); while(numTemp!=nThreadOrder[nThread]) { pthread_cond_wait(&pCond, &pMutex); } printf("%c",strThread[numTemp]); if(nThread==3) nThread=0; else nThread++; pthread_mutex_unlock(&pMutex); pthread_cond_broadcast(&pCond); } pthread_exit("thread exit"); } int main() { pthread_t thread[4]; void *pThreadReturn; pthread_mutex_init(&pMutex, NULL); pthread_cond_init(&pCond, NULL); int i=0; for(;i<4;i++) { pthread_create(&thread[i], NULL, threadFun, (void *)i); } for(i=0;i<4;i++) { pthread_join(thread[i], &pThreadReturn); } printf(" "); pthread_mutex_destroy(&pMutex); pthread_cond_destroy(&pCond); return 0; }
使用线程的互斥量及条件变量实现。