POSIX semaphores: synchronization problem

I have a problem with synchronization using posix semaphores. Here is the code I wrote

sem_t *sem1, *sem2;

void* test1() {
    int rv;

    while(1) {
        rv = sem_wait(sem1);
        printf("sem_wait(&sem1) = %d\n",rv);
        printf("test1\n");

        rv = sem_post(sem2);
        printf("sem_post(&sem2) = %d\n\n",rv);
    }
    return NULL;
}

void* test2() {

    while(1) {

        rv = sem_wait(sem2);
        printf("sem_wait(&sem2) = %d\n",rv);
        printf("test2\n");

        rv = sem_post(sem1);
        printf("sem_post(&sem1) = %d\n\n",rv);
    }
    return NULL;
}

int main (int argc, const char * argv[]) {

pthread_t t1,t2;

sem1 = sem_open("sem1", O_CREAT | O_EXCL, 0644, 1);

if (sem1 == SEM_FAILED){
    perror("sem1_init");
    sem_close(sem1);
    return;
}   

sem2 = sem_open("sem2", O_CREAT | O_EXCL, 0644, 0);
if (sem2 == SEM_FAILED){
    perror("sem2_init");
    sem_close(sem1);
    sem_close(sem2);
    return;
}

pthread_create(&t1, NULL, &test1, NULL);
pthread_create(&t2, NULL, &test2, NULL);

pthread_join(t1, NULL);
pthread_join(t2, NULL);

return 0;
}

I expected that since I initialized sem1to 1 and sem2to 0, there test1would be a first function to run, and then they would alternate until the end of time.
Instead, it does not work, I mean in the journal, which I read many times "test1", many times "test2", alternated for some time, and then again without any order. Can someone tell me where is my mistake?

ps. I don’t know if it can be useful, but I am running MacOSX 10.6.7


EDIT: , sem_init sem_getvalue ( MacOS), sem_open, , , .
, , - sem_open: , , , File exists. ?

. man-, sem_wait 0, , -1, . , 1 ( test2)?

+3
1

, , .

, t1, sem1, while, . sem_post (& sem1), .


: , . , sem_init OSX, , .


. sem_wait 1, , errno. != 0, . EINTR, , .

+1

All Articles