In c++ how do you declare a binary semaphore?
I am trying to declare a binary semaphore in C++.
Is there a way to do it by using Semaphore X; ? What is the 开发者_运维技巧header you need to include?Sorry ... I am using unix g++
The C++ language and standard libraries do not have any concept of semaphores, or even threads. The answer depends entirely on what platform you're working on; for instance, the Windows and Linux system APIs have support for semaphores.
Since C++2003 will be around for a while have a look at Boost.Thread
. You won't find a semaphore in there, but that is probably too low level for what you are trying to do anyway.
If the compiler you're using implements (at least the threading part of) the C++11 standard library, you'd use std::mutex X;
, or possibly std::recursive_mutex X;
, std::timed_mutex X;
or std::recursive_timed_mutex X;
, depending on what capabilities you want (lacking a statement to the indicate otherwise, I'd guess you want std::mutex
).
With an older library, you'd probably want to use the pthreads
equivalent. If you need to support Windows (which doesn't include pthreads natively), you could use Anthony Williams's pthreads-win32 package. This has two good points: first, it's native to Posix and Posix-like systems (e.g., Linux), and second, although it uses slightly different names, the basic idea is almost like what's in the C++11 standard library, it should be pretty easy to change to that when your compiler supports it.
Since C++20 this is now possible in standard C++. See https://en.cppreference.com/w/cpp/thread/counting_semaphore for reference and an example. It is supported by compilers: g++ 11, clang 11, msvc standard library 19.28
精彩评论