C++ 在多个线程中递减索引

C++ 在多个线程中递减索引,c++,multithreading,c++11,atomic,C++,Multithreading,C++11,Atomic,为了使用多线程处理数组中的数据,我希望使用索引访问数组的每个元素。每个线程递减索引,并使用其当前值处理数组中的相应数据。索引是一个原子整数,递减到-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

为了使用多线程处理数组中的数据,我希望使用索引访问数组的每个元素。每个线程递减索引,并使用其当前值处理数组中的相应数据。索引是一个原子整数,递减到-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();
   }
}
数据类型myData[最大数据计数];
原子数据索引;
无效进程_数组()
{
uint16\u t index=data\u index.fetch\u sub(1);//问题从这里开始!
//
如果(索引!=-1)
{ 
使用(myData[index])/处理索引中的数据
}
其他的
{
数据_指数=-1;
}
}
无效工作线程()
{
当(正在运行时){
等待_数据();
进程_数组();
}
}
问题是,多个线程可以从
数据索引中减去1,使其小于-1。我如何才能做到这一点?

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

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
    }
}

一个选项是使用
std::mutex
来保护计数器。然后,每个线程可以锁定互斥锁,检查当前计数器值,决定是否减小它,然后解锁互斥锁。“喜欢使用索引访问数组的每个元素。”-我建议您为每个线程指定一系列要处理的索引。通常的方法是为线程启动函数提供一个开始(通常是结束)值作为参数。要么使用互斥锁,要么重新构造代码以适应索引可能低于-1的事实。如果是某种标志终止了处理,只需更改检查,使其检查通常是否小于零。是的,就是这样!我在想我应该自己用
compare\u exchange
做些什么,但不知道如何使用它。谢谢