简体   繁体   English

使用互斥和信号量的屏障实现

[英]Barrier implementation using mutex & semaphore

This is an interview question : Implement the barrier between n threads using mutexes and semaphores. 这是一个采访问题:使用互斥量和信号量在n线程之间实现屏障。 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. 异常自然会解开作用域并调用析构函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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