开发者

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

开发者 https://www.devze.com 2023-02-02 00:39 出处:网络
Consider I have a struct: struct SimpleStruct { int x; 开发者_如何学Pythonint y; int z; } Now if I have 3 separate threads, each which only updates one of the x,y,z fields of the struct respectivel

Consider I have a struct:

struct SimpleStruct {
    int x;
  开发者_如何学Python  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?


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.


You can safely update x from one thread and y on another, but you cannot safely update x from 2 separate threads without synchronization of some sort.


As many people have said, it's safe if each thread only updates one of them (no collisions) - IF you have a coherent cache. If you're on a multiprocessor without cache coherency, things get trickier (and differ depending on whether you need write coherency or read coherency). Some architectures might need processor A to do a cache writeback before processor B can see it. Depending on the architecture, if A and B are writing to the same cache line, then a write by A could on rare occasion be "lost" and overwritten by the cacheline flush of B's write.

See for example DSP vs ARM coherency issues in DaVinci processors.

In most cases (coherent caches, threads within the same process, etc) this isn't an issue.


As long as they're only changing the content of the struct and not a pointer to the struct or something weird like that, I can't think of any problems with this.


It is definitely safe to update the different fields using different threads. But if the threads are using the same pointer (to a struct) to update the fields, make sure that no thread changes that pointer.


x, y, z are distinct variables and reside in distinct memory blocks. The fact that they are grouped into a structure doesn't change anything. It is safe to update x, y, z from multiple threads as long as the same variable is not updated by multiple threads and the updating thread doesn't try to read from the other two variables. Also, watch out for false sharing. If updating is performed inside a tight loop, false sharing could make multithreaded implementation slower than singlethreaded one.

0

精彩评论

暂无评论...
验证码 换一张
取 消