在 c++如何声明二进制信号量?
我正在尝试在 C++ 中声明一个二进制信号量。
有没有办法使用 Semaphore X 来做到这一点; ?
您需要包含什么标题?
抱歉...我正在使用 unix g++
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++
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C++语言和标准库没有任何信号量的概念,甚至没有线程的概念。答案完全取决于您正在使用的平台;例如,Windows 和 Linux 系统 API 支持信号量。
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.
由于 C++2003 将存在一段时间,请查看
Boost.Thread
。您不会在那里找到信号量,但这对于您想要做的事情来说可能太低了。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.如果您使用的编译器实现了 C++11 标准库(至少是线程部分),您可以使用
std::mutex X;
,或者可能使用std:: recursive_mutex X;
、std::timed_mutex X;
或std::recursive_timed_mutex X;
,具体取决于您想要的功能(缺少说明否则,我猜你想要std::mutex
)。对于较旧的库,您可能需要使用等效的
pthreads
。如果您需要支持 Windows(本身不包含 pthreads),您可以使用 Anthony Williams 的 pthreads-win32 包。这有两个优点:首先,它是 Posix 和类 Posix 系统(例如 Linux)原生的,其次,虽然它使用的名称略有不同,但基本思想几乎就像 C++11 标准库中的内容,它当你的编译器支持它时,应该很容易改变它。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 possiblystd::recursive_mutex X;
,std::timed_mutex X;
orstd::recursive_timed_mutex X;
, depending on what capabilities you want (lacking a statement to the indicate otherwise, I'd guess you wantstd::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.从 C++20 开始,这在标准 C++ 中是可能的。请参阅https://en.cppreference.com/w/cpp/thread/counting_semaphore 供参考和示例。支持的编译器:g++ 11、clang 11、msvc 标准库 19.28
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