简体   繁体   中英

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); 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.

As I understand it, the threads should wait at sem_wait() until the value is greater than zero. 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); allows all threads to get past my sem_wait() line.

Thank you to Duck for helping me out.

Apple gcc defines sem_init in semaphores.h, but it returns -1 - it's unimplemented. That is, you cannot have unnamed semaphores. Instead, use sem_open(name, options, initial value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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