[英]POSIX semaphores/threads not working correctly?
I have the following code: 我有以下代码:
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
sem_t semr;
void* func(void* i)
{
sem_wait(&semr);
printf("\nInstance %d running",*(int*)i);
//sem_post(&semr);
return NULL;
}
int main(void)
{
sem_init(&semr,0,1);
void* (*fp)(void*);
int s1,s2,s3,val=0;
pthread_t t1,t2,t3;
fp=&func;
val=1;
s1=pthread_create(&t1,NULL,fp,(void*)&val);
val=2;
s2=pthread_create(&t2,NULL,fp,(void*)&val);
val=3;
s3=pthread_create(&t3,NULL,fp,(void*)&val);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
return 0;
}
The first thread( t1
) executes successfully. 第一个线程(
t1
)成功执行。 The subsequent threads( t2
and t3
) though, are blocked, since I never sem_post
the semaphore. 但是,后续线程(
t2
和t3
)被阻塞了,因为我从不sem_post
信号量。 The pthread_join
s will make main()
wait for all 3 threads to terminate. pthread_join
s将使main()
等待所有3个线程终止。
Neither thread will output anything . 两个线程都不会输出任何东西 。 Not even
t1
s output(see question 1 below) 甚至没有
t1
的输出(请参阅下面的问题1)
removing all pthread_join
s has a better effect in terms of what I expect: t1
executes successfully and the command prompt is returned. 就我所期望的而言,删除所有
pthread_join
会有更好的效果: t1
成功执行,并返回命令提示符。
My questions: 我的问题:
According to the sample code on this page , main()
should wait for t2
and t3
to terminate (in addition to successfully executing t1
and outputting something ). 据上示例代码此页 ,
main()
应该等待t2
和t3
终止(除成功执行t1
和输出的东西 )。 Am I using pthread_join
incorrectly here? 我在这里错误地使用了
pthread_join
吗? What's happening? 发生了什么?
Why happens to the blocked threads( t2
and t3
)? 为什么发生阻塞的线程(
t2
和t3
)? Are the threads forced to terminate due to main()
returning? 线程是否由于
main()
返回而被迫终止?
You should ensure that anything you print is terminated (not followed) with a newline. 您应该确保所打印的任何内容都以换行符终止(而不是跟随)。
stdout
won't be flushed while main
is blocked waiting to join your threads. 当
main
被阻止等待加入您的线程时,不会刷新stdout
。 When you explicitly cancel the program, again, stdout
won't be flushed. 再次明确取消程序时,不会刷新
stdout
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.