Hi,
I have two Pthreads and two named semaphores, the semaphores are created within the threads, is there a way in which i can declare a semaphore in one thread and then open and use it in the other one ?

Thanks

Recommended Answers

All 5 Replies

Of course you can! That's the whole point of semaphores: to synchronize threads. A named semaphore is convenient because all you need to do is call sem_open with the same name and you get the same semaphore for two, three, four, or a gezillion threads.

From this link:

A named semaphore is identified by a name of the form /somename. Two processes can operate on the same named semaphore by passing the same name to sem_open(3).

[accidentaly double posted]

Thanks for the reply, I have tried to do this before asking, when i debug the code it says that namedsema2 is an undeclared identifer, how would i go about passing the semaphore from one thread to the other ?

class Thread1 : public PThread
{
public:
    Thread1() : PThread(8096, PThread::NoAutoDeleteThread) 
    {}

    virtual void Main()
    {
        PNamedSemaphore namedsema2(0, 1,"B");
        else 
        {
            result1 = true;
        }
        namedsema2.Wait();
        // create a NS for the other thread to open
    }
   
};

class Thread2 : public PThread
{
public:
    Thread2() : PThread(8096, PThread::NoAutoDeleteThread) 
    {}
    virtual void Main()
    { 
      if (namedsema2.Open("B"))
        {
            result2 = true;
        }
        else 
        {
            result2 = false;
        }
     
    }

The "name" of the semaphore is, in your code, the string "B", not the identifier namedsema2. Of course that variable is in Thread1 and will be undeclared in Thread2.

This is how it should be:

class Thread1 : public PThread
{
public:
    Thread1() : PThread(8096, PThread::NoAutoDeleteThread) 
    {}

    virtual void Main()
    {
        PNamedSemaphore namedsema2(0, 1,"B");
        namedsema2.Wait();
        std::cout << "Signal from Thread2 received!" << std::endl;
        // create a NS for the other thread to open
    }
   
};

class Thread2 : public PThread
{
public:
    Thread2() : PThread(8096, PThread::NoAutoDeleteThread) 
    {}
    virtual void Main()
    { 
      PNamedSemaphore namedsema2(0, 1,"B"); //sending the same name "B" will make both PNamedSemaphore objects refer to the same semaphore.
      namedsema2.Post();
    }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.