我是多线程编程的新手,对pthreads有疑问。

这是我运行的测试代码,我不了解其行为。有人可以照一下吗?

void *t1(void *args){
    printf("returning from t1\n");
    return;
}

void *t2(void *args){
    printf("returning from t2\n");
    return;
}

int main(){
    pthread_t thread1,thread2;
    int r1,r2;
    r1=pthread_create(&thread1,NULL,t1,NULL);
    r2=pthread_create(&thread2,NULL,t2,NULL);

    pthread_join(thread1,NULL);
 // pthread_join(thread2,NULL);

    return 0;
}

该程序的行为是下面显示的5个行为之一
murtuza@murtuza:FFTW$ ./ptest
returning from t2
returning from t1
murtuza@murtuza:FFTW$ ./ptest
returning from t1
returning from t2
murtuza@murtuza:FFTW$ ./ptest
returning from t1
murtuza@murtuza:FFTW$ ./ptest
returning from t2
returning from t2
murtuza@murtuza:FFTW$ ./ptest
returning from t1
returning from t2
returning from t2

我不了解第四和第五输出。为什么线程t2执行两次?当然,如果我取消注释pthread_join(&thread2,NULL,t2,NULL)该程序将正常运行,但是我对仅一个线程加入main()线程的情况特别感兴趣。

谢谢,
米尔

最佳答案

恐怕我无法复制您的问题。

我跑了:

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

void *t1(void *args){
    printf("returning from t1\n");
    return NULL;
}

void *t2(void *args){
    printf("returning from t2\n");
    return NULL;
}

int main(){
    pthread_t thread1,thread2;
    int r1,r2;
    r1=pthread_create(&thread1,NULL,t1,NULL);
    r2=pthread_create(&thread2,NULL,t2,NULL);

    pthread_join(thread1,NULL);
 // pthread_join(thread2,NULL);

    return 0;
}

如:
while (true) ; do ./ptest ; date ; done

并发现:t1,t2; t2,t1和t1。

但不要重复输入,也不要丢失t1。

抱歉。

也许您的线程库中有东西坏了,或者从线程过程中打印出来了?

关于c++ - pthreads和pthread_join函数的行为,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3824150/

10-16 06:59