简体   繁体   English

Posix信号量。 为什么我的线程不会像预期的那样在sem_wait()上等待?

[英]Posix Semaphores. Why will my threads not wait at sem_wait() like they're supposed to?

The code in question is: 有问题的代码是:

void insertIntoFinalArray(char * string) {
    sem_wait(&insert);
    if (finalarray == NULL) finalarray = (char **) malloc(sizeof(char *));
    else finalarray = (char **) realloc(finalarray, ((size_final + 1) * sizeof(char *)));

    finalarray[size_final] = (char *) malloc(sizeof(string) + 1);
    strcpy(finalarray[size_final], string);
    size_final++;
    sem_post(&insert);
}

insert is initialized as sem_init(&insert, 0, 0); insert初始化为sem_init(&insert, 0, 0); EDIT: this is supposed to be sem_init(&insert, 0, 1) I was code stirring and just didn't set it back... it doesn't work either way. 编辑:这应该是sem_init(&insert, 0, 1)我在代码搅拌,只是没有将其设置回...这两种方式均不起作用。

As I understand it, the threads should wait at sem_wait() until the value is greater than zero. 据我了解,线程应在sem_wait()处等待,直到该值大于零为止。 However, the debug shows multiple threads within the function. 但是,调试显示函数中有多个线程。 乌格

So am I just not understanding what a semaphore does or ? 因此,我只是不了解信号量是做什么的吗?

Edit: OS X doesn't support unnamed semaphores... However, even using insert = sem_open("insert", O_CREAT, 1); 编辑:OS X不支持未命名的信号量...但是,即使使用insert = sem_open("insert", O_CREAT, 1); allows all threads to get past my sem_wait() line. 允许所有线程通过我的sem_wait()行。

Thank you to Duck for helping me out. 谢谢鸭子帮助我。

Apple gcc defines sem_init in semaphores.h, but it returns -1 - it's unimplemented. Apple gcc在semaphores.h中定义了sem_init,但它返回-1-未实现。 That is, you cannot have unnamed semaphores. 也就是说,您不能有未命名的信号灯。 Instead, use sem_open(name, options, initial value); 而是使用sem_open(name, options, initial value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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