【发布时间】:2015-09-04 10:46:44
【问题描述】:
我正在考虑使用非常基本的有界(预分配)堆栈来以正确的 LIFO 顺序跟踪我的线程 ID。所以我想知道我的实现是否是线程安全的:
// we use maximum 8 workers
size_t idle_ids_stack[8];
// position current write happening at
std::atomic_uint_fast8_t idle_pos(0);
// this function is called by each thread when it is about to sleep
void register_idle(size_t thread_id)
{
std::atomic_thread_fence(std::memory_order_release);
idle_ids_stack[idle_pos.fetch_add(1, std::memory_order_relaxed)] = thread_id;
}
// this function can be called from anywhere at anytime
void wakeup_one()
{
uint_fast8_t old_pos(idle_pos.load(std::memory_order_relaxed));
std::atomic_thread_fence(std::memory_order_acquire);
size_t id;
do
{
if(old_pos == 0) return; // no idle threads in stack; exit;
id = idle_ids_stack[old_pos-1];
}
while (!idle_pos.compare_exchange_weak(old_pos, old_pos-1, std::memory_order_acquire, std::memory_order_relaxed));
// wakeup single thread
signal_thread(id);
}
【问题讨论】:
-
这可能更适合代码审查...
-
你应该很少使用栅栏。直接在原子变量上同步。
-
你可能想使用一些测试工具,例如:1024cores.net/home/relacy-race-detector
标签: c++ multithreading c++11 stack lock-free