Search code examples
c++c++11boost-mutexstdmutex

Iterating over vector in one thread while other may potentially change reference


I have a vector allow_list that is periodically updated in a thread while another serves a function that checks if a certain string is in that allow_list via:

if (std::find(allow_list->begin(), allow_list->end(), target_string) != allow_list->end()){
    allow = true;
}

Now, the other thread may do something like this

// Some operation to a vector called allow_list_updated
allow_list = allow_list_updated;

Should I add a mutex here to lock and unlock before and after these operations? My intuition tells me it's "ok" and shouldn't crash and burn but this seems like undefined behavior to me.


Solution

  • You have race condition and you need to lock. Simple rule if thread can read variable with non atomic write from another you have race on that variable. Another problem you need to lock all vector. If you have lots of reads and rare writes std::shared_mutex might be good idea. If allow_list that is periodically updated only from the edges, list would be better option for allow_list = allow_list_updated since to swap list you need to swap head and tail. Another potential advantage of list is lack of false sharing. Whatever you do your container and its protection should be in one class.