Reputation: 2267
When implementing condition variables into a Win32 C++ program, would it be better to use Win32 functions, classes, and data types (e.g. CreateThread
, SleepConditionVariableCS
, WaitForSingleObjectEx
, ReleaseMutex
, CONDITION_VARIABLE
) or those from the C++11 standard libraries (e.g. thread
, wait
, join
, unlock
, condition_variable
)?
Since the answer to this question is probably not binary, what considerations should one take into account when making such a decision?
Upvotes: 6
Views: 1585
Reputation: 2267
One consideration should be what your compiler can handle. For example, when you install MinGW on Windows, you can choose whether to install the API for POSIX threads or Win32 threads. On the other hand, if you use TDM-GCC, you should be aware that versions 4.7.1 and lower use Win32 threads, while versions 4.8.1 and higher use POSIX threads. And as woolstar mentioned above, if you're using Microsoft's compiler, you should check to see whether the bugs in its support for these classes have been worked out.
If your compiler supports POSIX threads, you can use the C++ thread classes of the Standard Library (e.g. thread
, mutex
, condition_variable
). If your compiler supports Win32 threads, you can use the Win32 thread functions.
In my case, I originally had TDM-GCC 4.7.1 and tried to use the C++ Standard Library classes, but that didn't work (for reasons explained above). So I installed MinGW by itself and chose "posix" in the "threads" option of the installer. Then I was able to use those classes.
Upvotes: 1
Reputation: 72044
The C++ synchronization mechanisms are designed to C++ principles. They free their resources in the destructor, and they also use RAII to ensure safe locking. They use exceptions to signal errors.
Essentially, they are much harder to use incorrectly than the function-based native Windows API. This means that if you can use them (your implementation supports them), you always should use them.
Oh, and they are cross-platform.
Upvotes: 6