【发布时间】:2016-10-17 10:49:58
【问题描述】:
我有一个线程保存资源(设备的 OpenCl 命令队列),但我想限制同时访问此资源的线程数(如果gpu 命令队列“已满”)。不幸的是,我对 c++11 原子操作比较陌生。所以我想知道以下源代码是否按预期工作。
class SpinSemaphore{
public:
SpinSemaphore(int max_count):
_cnt(0),
_max_cnt(max_count){}
bool try_lock(){
bool run = true;
while(run){
int cnt = _cnt.load();
if(++cnt > _max_cnt) return false;
run = !std::atomic_compare_exchange_weak(&_cnt, &cnt,
std::memory_order_acquire);
}
return true;
}
void unlock(){
--_cnt;
}
private:
std::atomic<int> _cnt;
int _max_cnt;
};
//
SpinSemaphore m(4);
void foo(){ //..
if(m.try_lock()){//..
my_queue.enqueueNDRangeKernel(/**/);
}
else
//fallback
}
【问题讨论】:
-
"multi-reader; no writer" - 不需要锁定吗?
-
目的是限制阅读器的数量。我改变了主题以强调这一点。
-
那么你想要的是一个信号量。 Here's 一个使用 std::condition 的 impl - 在 C++11 中可用
-
抱歉,好像是这样。我自己弄糊涂了。
标签: c++ multithreading c++11 atomic