Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrently updating different fields of a struct - is it safe?

Tags:

c

concurrency

Consider I have a struct:

struct SimpleStruct {
    int x;
    int y;
    int z;
}

Now if I have 3 separate threads, each which only updates one of the x,y,z fields of the struct respectively, is it safe to let them update concurrently, or should I use a mutex or something to stop that from happening?

like image 773
Magnus Avatar asked Dec 05 '22 00:12

Magnus


1 Answers

It is safe (structs are aligned).

However you should be careful about false sharing (see Herb Sutter's article about it): if the fields are in the same cache line the writes will be effectively serialized.

like image 159
Giuseppe Ottaviano Avatar answered Dec 07 '22 13:12

Giuseppe Ottaviano