gpt4 book ai didi

c++ - 在多个线程中递减索引

转载 作者:行者123 更新时间:2023-11-28 02:20:09 25 4
gpt4 key购买 nike

为了使用多线程处理数组中的数据,我想使用索引访问数组的每个元素。每个线程递减索引并使用其当前值来处理数组中的相应数据。索引是一个原子整数,递减到 -1(或 0xFF)。如何防止索引值小于-1?

data_type myData[MAX_DATA_COUNT];
std::atomic<uint16_t> data_index;

void process_array()
{
uint16_t index = data_index.fetch_sub(1); // problem starts here!
//
if(index != -1)
{
do_something_with(myData[index]); // process data at index
}
else
{
data_index = -1;
}
}

void worker_thread()
{
while(is_running){
wait_for_data();
process_array();
}
}

问题是多线程可以将data_index减1,使其小于-1。我该怎么做?

最佳答案

使用compare_exchange方法。这是仅在成功检查后才修改变量的标准方法。

void process_array()
{
uint16_t index = data_index.load();

while((index != -1) && !data_index.compare_exchange_weak(index, index - 1));

if(index != -1)
{
do_something_with(myData[index]); // process data at index
}
}

关于c++ - 在多个线程中递减索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32828374/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com