• 线程


    有四个线程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("
    ");
    
        pthread_mutex_destroy(&pMutex);
        pthread_cond_destroy(&pCond);
    
        return 0;
    }

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

  • 相关阅读:
    C++模板的声明与实现分离 编译错误详解
    C语言中数据类型的隐式转换
    UNIX 高手的 10 个习惯
    linux 信号量
    引用与数组
    Linux 的变量命名规则
    .bash_profile和.bashrc的区别(如何设置生效
    URAL 1053 Pinocchio
    URAL 1040 Airline Company
    URAL 1045 Funny Game
  • 原文地址:https://www.cnblogs.com/mr-redrum/p/3534706.html
Copyright © 2020-2023  润新知