Semaphore behaviour

From: Richy2004 (richard.scothern_at_gmail.com)
Date: 07/27/04

  • Next message: Andrei Voropaev: "Re: backtraces at runtime in Linux"
    Date: 27 Jul 2004 02:19:30 -0700
    
    

    Hi,

    I'm running the following code on Suse 9.1 on intel hardware:

    #include <iostream>
    using namespace std;
    #include <pthread.h>
    #include <semaphore.h>

    pthread_t id1, id2, id3, id4;
    sem_t semaphore;

    void* threadFunc(void* arg) {
    string message((char*)arg);
    sem_post(&semaphore);
    cout << "sem_post: " << message << endl;
    }

    void* threadFunc2(void* arg) {
    string message((char*)arg);
    sem_wait(&semaphore);
    cout << "sem_wait: " << message << endl;
    }

    int main() {
    pthread_create(&id1, NULL, threadFunc, (void*)"thread1");
    pthread_create(&id2, NULL, threadFunc2, (void*)"thread2");
    pthread_create(&id3, NULL, threadFunc2, (void*)"thread3");
    pthread_create(&id4, NULL, threadFunc, (void*)"thread4");
    return 0;
    }

    The output I'm seeing is:
    sem_post: thread1
    sem_wait: thread2
    sem_post: thread4

    I know the order is undefined, but I would expect thread3 to block, and
    then be run after thread4 increments the semaphore.
    Could anyone provide a pointer to what's happening?

    Thanks,
    Richard


  • Next message: Andrei Voropaev: "Re: backtraces at runtime in Linux"

    Relevant Pages