Updating various fields of a structure at the same time - is it safe?

I have a structure:

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

Now, if I have 3 separate threads, each of which only updates one of the fields x, y, z of the structure, is it safe to allow them to update at the same time or use a mutex or something to stop this from happening?

+4
source share
6 answers

It is safe (structures are aligned).

However, you should be careful with false communication (see the article by Herb Sutter ): if the fields are on the same line of the cache, the record will be effectively serialized.

+8
source

You can safely update x from one thread and y in another, but you cannot safely update x from 2 separate threads without any synchronization.

+3
source

Like many people, it is safe if each thread updates only one of them (no collisions) - IF you have a consistent cache. If you use a multiprocessor without cache matching, things get more complicated (and depends on whether you need write coherence or read consistency). Some architectures may require processor A to write the cache before processor B can see it. Depending on the architecture, if A and B write to the same cache line, then the A record may in rare cases be β€œlost” and overwritten by resetting the caching of the B record.

See, for example, DSP and ARM matching issues in DaVinci processors.

In most cases (coherent caches, threads within the same process, etc.) this is not a problem.

+2
source

As long as they change the contents of the structure, not the pointer to the structure or something strange, I can not think of any problems with this.

+1
source

It is definitely safe to update different fields using different threads. But if threads use the same pointer (for structure) to update fields, make sure the thread does not change this pointer.

+1
source

x, y, z are various variables and are located in different memory blocks. The fact that they are grouped into a structure does not change anything. It is safe to update x, y, z from multiple threads if the same variable is not updated by multiple threads, and the update thread does not try to read from two other variables. Also, watch out for false sharing. If an update is performed inside a hard loop, a false exchange can make a multi-threaded implementation slower than a single-line implementation.

+1
source

Source: https://habr.com/ru/post/1334101/


All Articles