Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print value of std::atomic<unsigned int>

I am using std::atomic<unsigned int> in my program. How can I print its value using printf? Because it doesn't work if I just use %u. I know I can use cout, but my program is littered with printf calls and I don't want to replace each of them. Previously I was using unsigned int instead of std::atomic<unsigned int> so I was just using %u and therefore printing worked fine.

like image 897
MetallicPriest Avatar asked Jun 27 '11 12:06

MetallicPriest


People also ask

What is std :: atomic in C++?

Each instantiation and full specialization of the std::atomic template defines an atomic type. Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.

How do you use Stdatomics?

If all you mean by "atomic" is "the object doesn't corrupt its internal state," then you can achieve this through std::atomic<> for single plain-old-data types that have no invariant between them (a doesn't depend on b) but you need a lock of some sort for any dependent rules you need to enforce.

How do you declare an atomic variable in C++?

In order to solve this problem, C++ offers atomic variables that are thread-safe. The atomic type is implemented using mutex locks. If one thread acquires the mutex lock, then no other thread can acquire it until it is released by that particular thread.

Why is std atomic not movable?

std::atomic is not copyable or movable because its copy constructor is deleted and no move constructor is defined.


2 Answers

another option, you can use load. E.g.:

std::atomic<unsigned int> a = { 42 };
printf("%u\n", a.load());
like image 148
dirac3000 Avatar answered Sep 22 '22 05:09

dirac3000


template<typename BaseType>
struct atomic
{
    operator BaseType () const volatile;
}

Use a typecast to pull out the underlying value.

printf("%u", unsigned(atomic_uint));
like image 33
John Kugelman Avatar answered Sep 19 '22 05:09

John Kugelman