在 c++如何声明二进制信号量?

发布于 2024-10-30 23:01:43 字数 107 浏览 4 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

若无相欠,怎会相见 2024-11-06 23:01:43

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.

小鸟爱天空丶 2024-11-06 23:01:43

由于 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.

许一世地老天荒 2024-11-06 23:01:43

如果您使用的编译器实现了 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 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.

≈。彩虹 2024-11-06 23:01:43

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文