std::atomic bool or Normal global bool is good in single thread?

I have global vaiable in a below thread (bool allow) which restrict client to wait (by assign allow=false) till it is completed. After completed allow =true

bool allow =true;
static void * mythread(void *arg)
{

/* here is  Lock mutex code */

 allow =false;(**non atomic**)

 system(command);

  allow =true;

/* here is Unlock Mutex code */

}



if(allow)
{

// validate thread output

}

else
{
// wait
}

My concern is should i use std::atomic for the global varibale or its good as bove

std::atomic<bool>allow(true);

static void * mythread(void *arg)
{

 /* here is  Lock mutex code */

allow.store(false, std::memory_order_seq_cst);

 system(command);

allow.store(true, std::memory_order_seq_cst);

/* here is Unlock Mutex code */

}

if(allow)
{

// validate thread output

}

else
{
// wait
}

If all access to the boolean is protected by a mutex, then it does not matter either way (in terms of correctness). Use the atomic<> or don't. The correctness of your code will not suffer.

But the performance might suffer, other than the fact that you are locking access to something that already has a mutex protecting it, std::atomic<> has the potential to use a mutex under the hood itself. std::atomic_flag however, is guaranteed to be lock-free. See the cppreference documentation for more.

If you have a single thread accessing that boolean, then no point having any synchronization at all.

链接地址: http://www.djcxy.com/p/30806.html

上一篇: std :: async有什么问题?

下一篇: std ::原子布尔或普通全局布尔是好的单线程?