【发布时间】:2013-12-30 08:23:16
【问题描述】:
前段时间面试,被要求实施
仅使用互斥操作和原语的信号量
(他允许 int 被认为是原子的)。我在下面提供了解决方案。
他不喜欢忙碌/等待部分——while (count >= size) {}——并要求通过使用更原始的方式来实现锁定
类型和互斥锁。我没有设法提供改进的解决方案。
有什么想法可以做到吗?
struct Semaphore {
int size;
atomic<int> count;
mutex updateMutex;
Semaphore(int n) : size(n) { count.store(0); }
void aquire() {
while (1) {
while (count >= size) {}
updateMutex.lock();
if (count >= size) {
updateMutex.unlock();
continue;
}
++count;
updateMutex.unlock();
break;
}
}
void release() {
updateMutex.lock();
if (count > 0) {
--count;
} // else log err
updateMutex.unlock();
}
};
【问题讨论】:
-
使用条件变量来消除忙等待。 en.cppreference.com/w/cpp/thread/condition_variable 还有你为什么不使用 RAII 来进行锁定/解锁。