在pthread示例中查询重新编码代码序列

时间:2015-05-13 03:59:59

标签: c multithreading pthreads

int loop = 4;

int a1=0,a2=10;
int b1=100,b2=1000;

int switchs=0;

void* runT1(void* args) {

    int i;
    for(i=0; i<loop; i++) {
        pthread_mutex_lock(&locks);
            while(switchs == 1) pthread_cond_wait(&conditions,&locks);
            printf("i=%d a1=%d\n",i,a1++);
            printf("i=%d a2=%d\n",i,a2++);
            switchs = 1;
            pthread_cond_signal(&conditions);
        pthread_mutex_unlock(&locks);
    }

    pthread_exit(NULL);
}

void* runT2(void* args) {

        int i;
        for(i=0; i<loop; i++) {
            pthread_mutex_lock(&locks);
                while(switchs == 0) pthread_cond_wait(&conditions,&locks);
                printf("i=%d b1=%d\n",i,b1++);
                printf("i=%d b2=%d\n",i,b2++);
                switchs = 0;
                pthread_cond_signal(&conditions);
            pthread_mutex_unlock(&locks);
        }

        pthread_exit(NULL);
}

void runs(void) {

    pthread_mutex_init(&locks,0);
    pthread_cond_init(&conditions,0);

    pthread_t T1,T2;

    pthread_create(&T1,NULL,runT1,NULL);
    pthread_create(&T2,NULL,runT2,NULL);

    pthread_join(&T1,NULL);
    pthread_join(&T2,NULL);

    pthread_mutex_destroy(&locks);
    pthread_cond_destroy(&conditions);
}

我从runs()调用main()方法。似乎没有给予期望 输出打印a1 a2 b1 b2依次4次。请帮忙!!!

1 个答案:

答案 0 :(得分:2)

通过少量修复程序来编译代码,它运行良好:

#include <pthread.h>
#include <stdio.h>

int loop = 4;

int a1=0,a2=10;
int b1=100,b2=1000;

int switchs=0;

pthread_mutex_t locks;
pthread_cond_t conditions;

void* runT1(void* args) {

    int i;
    for(i=0; i<loop; i++) {
    pthread_mutex_lock(&locks);
        while(switchs == 1) pthread_cond_wait(&conditions,&locks);
        printf("i=%d a1=%d\n",i,a1++);
        printf("i=%d a2=%d\n",i,a2++);
        switchs = 1;
        pthread_cond_signal(&conditions);
    pthread_mutex_unlock(&locks);
    }

    pthread_exit(NULL);
}

void* runT2(void* args) {

    int i;
    for(i=0; i<loop; i++) {
        pthread_mutex_lock(&locks);
        while(switchs == 0) pthread_cond_wait(&conditions,&locks);
        printf("i=%d b1=%d\n",i,b1++);
        printf("i=%d b2=%d\n",i,b2++);
        switchs = 0;
        pthread_cond_signal(&conditions);
        pthread_mutex_unlock(&locks);
    }

    pthread_exit(NULL);
}

int main(void) {

    pthread_mutex_init(&locks,0);
    pthread_cond_init(&conditions,0);

    pthread_t T1,T2;

    pthread_create(&T1,NULL,runT1,NULL);
    pthread_create(&T2,NULL,runT2,NULL);

    void *j;
    pthread_join(T1,&j);
    pthread_join(T2,&j);

    pthread_mutex_destroy(&locks);
    pthread_cond_destroy(&conditions);
    return 0;
}

输出:

  

i = 0 a1 = 0
  i = 0 a2 = 10
  i = 0 b1 = 100
  i = 0 b2 = 1000
  i = 1 a1 = 1
  i = 1 a2 = 11
  i = 1 b1 = 101
  i = 1 b2 = 1001
  i = 2 a1 = 2
  i = 2 a2 = 12
  i = 2 b1 = 102
  i = 2 b2 = 1002
  i = 3 a1 = 3
  i = 3 a2 = 13
  i = 3 b1 = 103
  i = 3 b2 = 1003