Category : volatile

Recently Eric Niebler had a tweet about volatile and thread safety and somebody replied with the link to following code from Intel TBB. void Block::shareOrphaned(intptr_t binTag, unsigned index) { MALLOC_ASSERT( binTag, ASSERT_TEXT ); // unreferenced formal parameter warning tbb::detail::suppress_unused_warning(index); STAT_increment(getThreadId(), index, freeBlockPublic); markOrphaned(); if ((intptr_t)nextPrivatizable==binTag) { // First check passed: the block is not in ..

Read more

C++20 deprecated some certain operations on volatile types (following P1152). The following code, that was valid prior to C++20: void busyLoop(std::size_t count) { for (volatile size_t counter = 0; counter < count; ++counter); } now generates a deprecation warning: warning: ‘++’ expression of ‘volatile’-qualified type is deprecated [-Wvolatile] Changing the ++ to += or to ..

Read more

Suppose I have a struct like this volatile struct { int foo; int bar; } data; data.foo=1; data.bar=2; data.foo=3; data.bar=4; Are the assignments all guaranteed not to be reordered? For example without volatile the compiler would clearly be allowed to optimize it as two instructions in a different order like this: data.bar=4; data.foo=3; But with ..

Read more

Suppose I have a struct like this: volatile struct { int foo; int bar; } data; data.foo=1; data.bar=2; data.foo=3; data.bar=4; Are the assignments all guaranteed not to be reordered? For example without volatile, the compiler would clearly be allowed to optimize it as two instructions in a different order like this: data.bar=4; data.foo=3; But with ..

Read more

#include <iostream> #include<thread> #include <initializer_list> #include <vector> #include <future> #include <time.h> using namespace std; class Gadget{ public: Gadget(){ flag_ = false; cout<<"Creating new Gadgets"<<endl; } void wait(){ while(flag_==false){ cout<<"waiting here…."<<endl; this_thread::sleep_for(chrono::milliseconds(1000)); } } void wake(){ flag_ = true; } private: volatile bool flag_; }; I am trying to make two threads and one thread will ..

Read more