FAQ Database Discussion Community


Is it possible to restrict a member function from accessing a member variable?

c++,multithreading,thread-safety,chrono,stdatomic
I have a thread class similar to this: class thr { void run() { for (;;) { // block on a queue // do some processing ++loops_; } } void get_metrics(int& qps) { std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); double delta = std::chrono::duration<double>(now - last_metrics_time_).count(); qps = std::round(loops_ / delta); loops_ =...

Is fetch_sub really atomic?

c++,multithreading,reference-counting,stdatomic
I have the following code (written in C++): Code in StringRef class: inline void retain() const { m_refCount.fetch_add(1, std::memory_order_relaxed); } inline void release() const { if(m_refCount.fetch_sub(1, std::memory_order_release) == 1){ std::atomic_thread_fence(std::memory_order_acquire); deleteFromParent(); } } Code in InternedString: public: inline InternedString(){ m_ref = nullptr; } inline InternedString(const InternedString& other){ m_ref = other.m_ref;...

Understanding why race condition happens when only one thread does the write operation

exception,c++11,race-condition,raii,stdatomic
I recently asked "Thrown object cannot be caught in a multi-threaded solution" and got the correct answer which works perfectly. However, I am still confused why there can be a race condition when only one thread does the write operation. Let me paste the original problematic code: #include <iostream> #include...

Issue using std::atomic_flag with worker thread

c++,multithreading,c++11,stdatomic
sorry for the verbosity - I did my best to condense my code sample into a minimally functional class and main() method. I'm trying to use an atomic_flag to notify _rx() within my worker thread to quit when stop() is called. I believe the issue is in trying to create...

Is it safe to use the Structure dereference(->) operator on the result of std::atomic::load

c++,c++11,atomic,stdatomic
Whilst trying to work with std atomic pointer, I ran into the following. Say I do this: std::atomic<std::string*> myString; // <do fancy stuff with the string... also on other threads> //A can I do this? myString.load()->size() //B can I do this? char myFifthChar = *(myString.load()->c_str() + 5); //C can I...

Read a variable in another thread

multithreading,c++11,atomic,stdatomic
I'm using linux and I have two variable that is read/write in another thread. Once in a while (100ms) ThreadB reads the status of the variables and does something. It's basically a while(1){ dosomething(); usleep(); }. I'm worried the variables will be cached and never updated. What's the best way...