Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

are c++ pointers to user-defined objects thread safe for reading?

I can't find the answer but it's a simple question:

Is it safe for two threads to read the value of a pointer to a user-defined object in c++ at the same time with no locks or any other shenanigans?

like image 635
paul13243546 Avatar asked Dec 12 '22 18:12

paul13243546


2 Answers

Yes. Actually it is safe to read any values (of builtin type) concurrently.

Data races can only occur, if a value is modified concurrently with some other thread using it. The key statements from the Standard for this are:

A data race is defined in §1.10/21:

The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other.

where conflicting is defined in §1.10/4:

Two expression evaluations conflict if one of them modifies a memory location (1.7) and the other one accesses or modifies the same memory location.

So you must use suitable synchronization between those reads and any writes.

like image 88
JoergB Avatar answered Jan 04 '23 22:01

JoergB


It is always safe to read values from multiple threads. It's only when you're also writing to the data that you need to manage concurrent accesses.

The only possible issue for read-only data is ensuring that the value has, in fact, been initialized when the reading is done. If you initialize the value before you start your threads you'll be fine.

like image 41
Pete Becker Avatar answered Jan 04 '23 22:01

Pete Becker