lundi 28 septembre 2015

Decrementing an index in multiple threads

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?

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

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

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?

Aucun commentaire:

Enregistrer un commentaire