coder_new

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

有四个线程1、234。线程1的功能就是输出1,线程2的功能就是输出2,以此类推.........现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:

A1 2 3 4 1 2....

B2 3 4 1 2 3....

C3 4 1 2 3 4....

D4 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("\n");

    pthread_mutex_destroy(&pMutex);
    pthread_cond_destroy(&pCond);

    return 0;
}

使用线程的互斥量及条件变量实现。

posted on 2014-06-25 15:26  coder_new  阅读(215)  评论(0编辑  收藏  举报