TheMeaningfulEngineer
TheMeaningfulEngineer

Reputation: 16359

Can read happen in true parallelism?

If there are multiple threads running on separate cores (true parallelism) and they access the same variable all in the same time. If they are guaranteed to just read the variable, can the read happen in true parallelism?

Consider the following example:

If we define the access function to that variable (called bool stop) as:

bool const & readOnlyAccesToVariable()  // Returns a unchangeble reference to the variable 

The variable is private to a master thread. The duty of a master thread is to stop the execution of a large number of worker threads on separate cores as simultaneously as possible. The workers are stopped if the stop changes to 1.

The worker periodically does:

if (readOnlyAccesToVariable() ) break;

Will some of the workers bi stopped simultaneously (meaning that the read of stop is not serialized but parallel)?

Upvotes: 0

Views: 181

Answers (2)

Werner Henze
Werner Henze

Reputation: 16771

I don't quite understand your problem.

You want to terminate a lot of worker threads by setting a stop variable to true. This is fine, but please don't forget to make stop volatile so the compiler knows that the value of stop can change anytime and it must reread stop every time it has to access it (and not use value it might have just written to a register).

You also say that you need to terminate all threads as parallel as possible. First of all I do not understand why you need to do so. Second I don't understand why you are doing a polling mechanism when you need all threads to terminate exactly the same time. Why don't you use an event, set that and let the operating system wake up all threads waiting on the event? If you can't do so because your threads are not just waiting for the stop event but also doing things, then again I do not understand your requirements. If the threads are doing things and from time to time check the stop variable, then how do you want to achieve absolut parallel termination? This seems quite contradictory.

Upvotes: 1

Adam
Adam

Reputation: 17379

As long as no thread will modify the value, reads are perfectly ok.

An immutable variable by definition cannot be written, so yes that makes it thread safe in that respect.

However you of course have to make sure it gets initialized in a thread-safe way, and that no threads will start reading until it has been initialized.

Upvotes: 2

Related Questions