is assignment operator '=' atomic?

前端 未结 4 777
面向向阳花
面向向阳花 2020-12-02 17:15

I\'m implementing Inter-Thread Communication using global variable.

//global var
volatile bool is_true = true;

//thread 1
void thread_1()
{
    while(1){
           


        
4条回答
  •  广开言路
    2020-12-02 18:01

    The thread safeness of this piece of code does not depend on atomicity of the assignment. Both thread routines work strictly in turn. There is no race condition: thread_1 will output stuff until getting certain random number after which it will leave the 'output section' and let the other thread work in it. There are a couple of things worth noting though:

    • rand() function may be not thread-safe (not the problem in the code given here though)
    • you should not use Win32 function CreateThread(), especially when you are using CRT libraly functions which (potentially) utilize global variables. Use _beginthreadex() instead.

提交回复
热议问题