I found myself needing a threadsafe global variable to indicate when a thread is complete.
Quickly discovered std::atomic<type> var(val); only to find it has no support in my IDE.

Can anyone offer an alternative?

I have an operation that needs to be carried out which takes some time, I cannot afford that time in current thread and want to subcontract the work to another thread.

I'm going to be using global variable(s) (not sure if I can use static) to which the thread can deposit the result(s).
And of course I need a safe way to know when the spawned thread is complete.

Thank you for taking time to read.

Recommended Answers

All 3 Replies

For pre-C++11 compilers, i.e. C++03 compilers, you should use the Boost libraries, which is where all the standard library additions came from, and will likely come from in the future. In this case, the Boost.Thread library is what you are looking for.

However, I doubt that your idea is really the best way to achieve what you want. To me, it sounds like the appropriate solution is the "futures and promises" method. See the boost::future documentation for example. The idea is pretty simple, you create a "promise" and an associated "future" (expectation of a value being delivered). The thread takes the "promise" and is responsible for fulfilling it at some point (i.e., giving it a value). The "main" thread keeps the "future" and can either wait for it to be fulfilled or regularly check it. The reason for this separation has to do with avoiding locks, probably in a similar way as you were thinking of using atomics.

By the way, standard atomics only work for trivially copyable types.

Thank's for reply and suggestion, I appreciate your time.

I have heard much about boost and seen many answers around which recerence it.

The Boost library does some pretty amazing stuff. It is commonly used by the HEP (High Energy Physics) programming community, which should indicate its capability and quality - these are people who would rather program directly in Fortan than C++, but had eschewed Fortran for C++ with Boost over the past 10-20 years. FWIW, my wife is a particle physicist and computing division staff member at Fermi National Lab here in Batavia, Illinois. This is from her lips! :-)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.