简体   繁体   English

POSIX信号/线程无法正常工作?

[英]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;
}

This is my understanding of what happens: 这是我对发生的事情的理解:

The first thread( t1 ) executes successfully. 第一个线程( t1 )成功执行。 The subsequent threads( t2 and t3 ) though, are blocked, since I never sem_post the semaphore. 但是,后续线程( t2t3 )被阻塞了,因为我从不sem_post信号量。 The pthread_join s will make main() wait for all 3 threads to terminate. pthread_join s将使main()等待所有3个线程终止。

This is what happens: 这是发生了什么:

Neither thread will output anything . 两个线程都不会输出任何东西 Not even t1 s output(see question 1 below) 甚至没有t1的输出(请参阅下面的问题1)

However, 然而,

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: 我的问题:

  1. 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()应该等待t2t3终止(除成功执行t1 输出的东西 )。 Am I using pthread_join incorrectly here? 我在这里错误地使用了pthread_join吗? What's happening? 发生了什么?

  2. Why happens to the blocked threads( t2 and t3 )? 为什么发生阻塞的线程( t2t3 )? 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM