C ++ Best way to share state between threads

The scenario is as follows: Thread A continues to run until it receives a stop signal from thread B, which continues to read input from the console.

What is the best way to implement this? For example, I think that I could implement it as a global variable that thread A checks every once in a while, and thread B can change to a stop signal,

But I do not know if this is correct.

  • Even if this is correct, should I use "Volatile" or "Atomic <>"? Especially that stream A only reads the value of the variable, and stream B writes only the variable.

  • And what if changing a variable from thread B right after thread A has read it does not matter (it does not cause a problem thread). Is the exit time somewhat relaxed (allowed after the signal)?)?

  • Is there any other way for thread B to start thread A and stop it when it wants?

+4
source share
4 answers

The question will probably be closed as "too wide", but I will try to answer it (in the same "wide" form). A.

The only possible answer here is: “it depends” (c)

< > : , ? : , ? : , ? >

: ( KISS). (, ), - , , , /// (, ). - , ( , , concurrency, ), .

+5

, , , .

. . . , . , , . .

. , , , .

. . int, , , .

int . , . , , , . , . , , , .

, .

, , A , . B, , . , . B A. , - - , .

+2

volatile, , , . , , std:: atomic_bool.

+1

You can use a variable to signal a stop, as you explained, but only if you use memory barriers.

For more information, see Understanding C ++ 11 Screensavers .

0
source

All Articles