如何打印此代码1 2 3 4 5 6

时间:2014-05-08 06:22:26

标签: c pthreads mutex

我已更改此代码,但无法打印1 2 3 4 5 6 缺什么?? 我试图在每个线程创建之间放两个互斥锁,在打印它们时另外放一个互斥锁,但我总是得到3 4 5 6 1 2。 提前谢谢。

pthread_mutex_t mutex;
pthread_mutex_t mutexd;
void *th(void *arg){
int *tmp=(int*)arg;
    pthread_mutex_lock(&mutexd);
    printf("%d\t",tmp[0]);
    printf("%d\t",tmp[1]);
    pthread_mutex_unlock(&mutexd);

}

int main(){
    pthread_mutex_init(&mutex,NULL);
    pthread_mutex_init(&mutexd,NULL);

    pthread_t threads[3];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
    pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);
    int t[]={1,2,3,4,5,6};
    pthread_mutex_lock(&mutex);
    pthread_create(&threads[0],&attr,th,(void *)t);
    pthread_mutex_unlock(&mutex);
    pthread_mutex_lock(&mutex);
    pthread_create(&threads[1],&attr,th,(void *)(t+2));
     pthread_mutex_unlock(&mutex);
    pthread_mutex_lock(&mutex);

    pthread_create(&threads[2],&attr,th,(void *)(t+4));
      pthread_mutex_unlock(&mutex);

    int i;
    for(i=0;i<THREADS;i++){
            pthread_join(threads[i],NULL);
    }
    putchar('\n');
    return 0;


}

1 个答案:

答案 0 :(得分:0)

线程通常不会按照它们在代码中编写的顺序工作。为了实现此移动,每个连接都在创建线程之后。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
pthread_mutex_t mutex;
pthread_mutex_t mutexd;
void *th(void *arg)
{
    int *tmp=(int*)arg;

    pthread_mutex_lock(&mutexd);
    printf("%d\t",tmp[0]);
    printf("%d\t",tmp[1]);

    pthread_mutex_unlock(&mutexd);

}

int main()
{
    pthread_mutex_init(&mutex,NULL);
    pthread_mutex_init(&mutexd,NULL);

    pthread_t threads[3];
    pthread_attr_t attr;
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
    pthread_attr_setscope(&attr,PTHREAD_SCOPE_SYSTEM);


    int t[]= {1,2,3,4,5,6};

    pthread_mutex_lock(&mutex);

    pthread_create(&threads[0],&attr,th,(void *)t);
     pthread_join(threads[0],NULL);
    pthread_mutex_unlock(&mutex);

    pthread_mutex_lock(&mutex);
    pthread_create(&threads[1],&attr,th,(void *)(t+2));
     pthread_join(threads[1],NULL);
    pthread_mutex_unlock(&mutex);

    pthread_mutex_lock(&mutex);
    pthread_create(&threads[2],&attr,th,(void *)(t+4));
     pthread_join(threads[2],NULL);
    pthread_mutex_unlock(&mutex);

    putchar('\n');
    return 0;


}

此代码应该可以正常工作