简体   繁体   中英

Barrier implementation using mutex & semaphore

This is an interview question : Implement the barrier between n threads using mutexes and semaphores. The solution I proposed :

class Barrier {
public:
Barrier(unsigned int n) : _n(n),_count(0),_s(0) {}
~Barrier() {}
void Wait() {
     _m.lock();
       _count++;
       if (_count == _n) { _s.signal(); }
     _m.unlock();
     _s.wait();
     _s.signal();
}
private:
   unigned int _n;
   unigned int _count;
   Mutex _m;
   Semaphore _s;
};

Is that solution Ok? Can the Barrier be implemented using mutexes only?

Mutexes are exactly for only allowing one thread to execute a chunk of code and block other threads. I've always used or made classes that lock / unlock by scope on the constructor and destructor. You'd use it like this:

void workToDo()
{
    CMutex mutex(sharedLockingObject);

    // do your code
}

When the method finishes, the mutex goes out of scope, and calls the destructor. The constructor performs a blocking lock and does not unblock until the lock is acquired. This way you don't have to worry about exceptions leaving you with locked mutexes that blocks code when it shouldn't. The exception will naturally unravel the scope and call the destructors.

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