sem_wait not working in basic code

风格不统一 提交于 2019-12-24 04:13:30

问题


Compiled with gcc. I ran this to see why the semaphores I was using in my other programs were not working correctly. Am I just using these them incorrectly or what? The string is outputted every time even though the semaphore should halt execution and cause a deadlock, right?

Here is the code:

#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#define NUM_THREADS 5
void printHello();
int main(){
    int i;
    pthread_t threads[NUM_THREADS];
    sem_t sem1;
    sem_init(&sem1, 0, 0);
    sem_wait(&sem1);

    for(i = 0; i < NUM_THREADS; i++){
        pthread_create(&threads[i], NULL, &printHello, NULL);
    }

    sem_destroy(&sem1);
    pthread_exit(NULL); 

        return 0;
}

void printHello(){
    printf("sem_wait failed\n");
}

Any help would be greatly appreciated as I am trying to grasp the whole multithreading concept.

Thanks!


回答1:


That code looks fine. Well, it will after you change the start function to void *printHello(void *) and pthread_join so you don't destroy the semaphore and exit. But the semaphore blocks exactly as it should on linux.

Are you running on OSX? Apparently OSX does not support unnamed POSIX semaphores. If that is the case you need to use named POSIX semaphores i.e. sem_open rather than sem_init.



来源:https://stackoverflow.com/questions/20850750/sem-wait-not-working-in-basic-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!