Question

I have two C++ classes, objecManip and updater. The updater class has a timer to check the status of the robot arm of my application.

If it moving then do nothing, else getNextAction() from the actions queue.

The actions queue is populated with class objectManip. I have a global variable: current_status of the robot arm that I need in objectManip.

The problem is that when filling in actions queue current_status is taken constantly not dynamically.

Was it helpful?

Solution

Question is very unclear, so this is really a stab in the dark, but you need to use atomic data types. With C++11, you have std::atomic (see here or here. For an earlier version of C++, I think you need to use some library or compiler specific data type, which offers atomic data types.

If you make some assumptions about how multithreading works for your CPU and operating system, you may get away with just declaring shared variables volatile and reading value to temp variable when you use it. volatile is really meant for cases like reading hardware-mapped values, where value must be read from the memory every time, so many optimizations are not possible. It does not guarantee atomic updates in itself, because a thread modifying a value may be interrupted in the middle of update, and then another read may read invalid, partially updated value. For booleans this should be fairly safe. For integers which do not cross memory word boundary and which word size or less, this may be safe on many CPUs, which will not interrupt a thread in the middle of writing single memory word. Otherwise, it is data corruption waiting to happen. Some (today uncommon) CPUs also do not synchronize caches between multiple CPU cores, and in that case volatile will not help, different threads may see different cached value. So conclusion: use volatile as last resort hack!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top