前段时间进行了一次采访,并被要求仅使用互斥锁操作和基元来实现信号量(他允许将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();
}
};
Run Code Online (Sandbox Code Playgroud)