wait and notify in C/C++ shared memory(在 C/C++ 共享内存中等待和通知)
问题描述
How to wait and notify like in Java In C/C++ for shared memory between two or more thread?I use pthread library.
Instead of the Java object that you would use to wait/notify, you need two objects: a mutex and a condition variable. These are initialized with pthread_mutex_init
and pthread_cond_init
.
Where you would have synchronized on the Java object, use pthread_mutex_lock
and pthread_mutex_unlock
(note that in C you have to pair these yourself manually). If you don't need to wait/notify, just lock/unlock, then you don't need the condition variable, just the mutex. Bear in mind that mutexes are not necessarily "recursive", This means that if you're already holding the lock, you can't take it again unless you set the init flag to say you want that behaviour.
Where you would have called java.lang.Object.wait
, call pthread_cond_wait
or pthread_cond_timedwait
.
Where you would have called java.lang.Object.notify
, call pthread_cond_signal
.
Where you would have called java.lang.Object.notifyAll
, call pthread_cond_broadcast
.
As in Java, spurious wakeups are possible from the wait functions, so you need some condition which is set before the call to signal, and checked after the call to wait, and you need to call pthread_cond_wait
in a loop. As in Java, the mutex is released while you're waiting.
Unlike Java, where you can't call notify
unless you hold the monitor, you can actually call pthread_cond_signal
without holding the mutex. It normally doesn't gain you anything, though, and is often a really bad idea (because normally you want to lock - set condition - signal - unlock). So it's best just to ignore it and treat it like Java.
There's not really much more to it, the basic pattern is the same as Java, and not by coincidence. Do read the documentation for all those functions, though, because there are various flags and funny behaviours that you want to know about and/or avoid.
In C++ you can do a bit better than just using the pthreads API. You should at least apply RAII to the mutex lock/unlock, but depending what C++ libraries you can use, you might be better off using a more C++-ish wrapper for the pthreads functions.
这篇关于在 C/C++ 共享内存中等待和通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C/C++ 共享内存中等待和通知


基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17