减少多个线程中的索引

时间:2023-01-28 10:46:58

In order to process data in an array using multithreading, I'd like to access each element of the array using an index. Each thread decrements the index and uses its current value to process the corresponding data in the array. The index is an atomic integer and decremented until it's -1 (or 0xFF). How can I prevent the value of the index to become less than -1?

为了使用多线程处理数组中的数据,我想使用索引访问数组的每个元素。每个线程递减索引并使用其当前值来处理数组中的相应数据。索引是一个原子整数并递减,直到它为-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();
   }
}

The problem is that multiple threads can subtract 1 from data_index and make it less than -1. How can I do this?

问题是多个线程可以从data_index中减去1并使其小于-1。我怎样才能做到这一点?

1 个解决方案

#1


2  

Use compare_exchange method. This is a standard way for modify variable only after successfull check.

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

#1


2  

Use compare_exchange method. This is a standard way for modify variable only after successfull check.

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