问题描述
我是新的多线程编程,并有一个关于pthreads的问题。
这是我运行的测试代码,我不明白它的行为。
void * t1(void * args){
printf from t1\\\
);
return;
}
void * t2(void * args){
printf(从t2\\\
返回);
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
从t2返回
从t1返回
murtuza @ murtuza :FFTW $ ./ptest
从t1返回
从t2返回
murtuza @ murtuza:FFTW $ ./ptest
从t1返回
murtuza @ murtuza:FFTW $ ./ptest
从t2返回
从t2返回
murtuza @ murtuza:FFTW $ ./ptest
从t1返回
从t2返回
从t2
我不明白第4和第5个输出。为什么线程t2执行两次?当然,如果我取消注释 pthread_join(& thread2,NULL,t2,NULL)
程序将正常运行,但我特别感兴趣的情况下,
感谢,
Mir
我想您希望我们在这里解释未定义的行为。在您离开 main()
后,不应使用任何C库函数。我认为你正在看到的是 main()
线程刷新缓冲区,而它正在关闭C库。我认为它可能在它关闭时忽略任何流锁。
I am new to multi-threaded programming and have a question about pthreads.
This is the test code that I run and I don't understand its behaviour. Can someone throw some light on it please.
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;
}
The behaviour of this program is either of the 5 shown below
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
I don't understand the 4th and 5th output. Why is thread t2 executing twice? Of course, if I uncomment pthread_join(&thread2,NULL,t2,NULL)
the program will behave correctly but I am specifically interested in the case where only one thread joins the main() thread.
thanks,Mir
I think you want us to explain undefined behaviour here. You should never use any C library function after you leave main()
. I think that what you are seeing is the main()
thread flushing buffers while it is shutting down the C library. I think it might be ignoring any streams locks at the time it is shutting down.
这篇关于pthread和pthread_join函数的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!