I'm not extensively knowledgeable in terms on the thread.h api of the C++11 (in fact I'm not familiar with thread progranmming either, but I read on it recently quite a lot and know about the concurrency and stuff like that) but I started using it and I'm facing a problem that I haven't really ever faced yet.
I have two thread functions, say these
std::thread(thread1, args); // Spawn thread 1
std::thread(thread2, args); // Spawn thread 2
[...]
int thread1(bunch of args)
{
lock_thread_2();
[do stuff]
while (some condition) {
[do stuff]
unlock_thread_2();
}
}
int thread2(bunch of args)
{
while (some condition) {
[do stuff]
wait_for_thread1_to_unlock_me();
}
}
I first thought about doing it with a std::mutex but I read it could be dangerous because the behavior is undefined if I unlock an already-unlocked mutex and on top of it it wouldn't work anyways as mutex.lock() doesn't necessarily pause the execution (it only does if the mutex is already locked) so it'd be quite horrendous to write, I'd have to couple unlock() and lock() calls together.
What's important to note here is that thread2's execution only is controlled by thread1, but thread2 will never lock thread1 in any fashion. Only thread2 gets locked by thread1, only thread1 controls the execution flow thread2, not otherwise.
How would you do that in a clean way, supported way? Would you be kind enough to give an example of code?
Thanks!
A lock_guard always holds a lock from its construction to its destruction. A unique_lock can be created without immediately locking, can unlock at any point in its existence, and can transfer ownership of the lock from one instance to another.
Would multiple threads each modifying a different array element be writing to the same location in memory? The answer is no. Each array element has a region of memory reserved for it alone within the region attributed the overall array.
A normal mutex cannot be locked repeatedly by the owner. Attempts by a thread to relock an already held mutex, or to lock a mutex that was held by another thread when that thread terminated, cause a deadlock condition. A recursive mutex can be locked repeatedly by the owner.
std::unique_lock The class unique_lock is a general-purpose mutex ownership wrapper allowing deferred locking, time-constrained attempts at locking, recursive locking, transfer of lock ownership, and use with condition variables.
Use a condition_variable
:
std::condition_variable cv;
int thread1(bunch of args)
{
[do stuff]
while (some condition) {
[do stuff]
cv.notify_one();
}
}
int thread2(bunch of args)
{
std::mutex mtx;
std::unique_lock<std::mutex> lk(mtx);
while (some condition) {
[do stuff]
cv.wait(lk);
}
}
When wait()
returns, either cv
will have been notify()
-ed... or there will have been a spurious wakeup. In an effort to handle the latter, it's often helpful to add a predicate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With