[英]use condition variable instead of lock_guard
I have a simple program in which I want to output the numbers 1-100, with one thread outputting all the odd numbers and the other one all even numbers. 我有一个简单的程序,我要输出1-100,一个线程输出所有的奇数,另一个输出所有的偶数。 Using lock_guard, this is quite an easy task.
使用lock_guard,这是一个非常容易的任务。 Code follows:
代码如下:
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <thread>
std::mutex m;
void print_numbers(int i)
{
for (i; i <= 100; i++)
{
std::lock_guard<std::mutex> locker(m);
std::cout << i << std::endl;
++i;
}
}
int main()
{
std::thread t1(print_numbers, 0);
std::thread t2(print_numbers, 1);
t1.join();
t2.join();
return 0;
}
My question is, how can I use condition variables to do this, and perhaps make it a little more elegant? 我的问题是,我该如何使用条件变量来做到这一点,或者使它更加优雅?
There is no sharing whatsoever in your code. 您的代码中没有任何共享。 Each thread has a local variable i.
每个线程都有一个局部变量i。 A POSIX condition is used for inter-thread communication/signaling.
POSIX条件用于线程间通信/信号传输。 The idea is simple:
这个想法很简单:
a thread check a boolean predicates (depending on a shared state) and decide to "wait" when the predicate is false (pthread_cond_wait in POSIX) 线程检查布尔谓词(取决于共享状态),并在谓词为假时决定“等待”(POSIX中的pthread_cond_wait)
another thread can modify the shared state and therefore impact the value of the boolean predicate. 另一个线程可以修改共享状态,因此会影响布尔谓词的值。 If this thread changes the state, it can notify the other thread (Thread #1) that it should wake up and re-check its predicate whose value might have now changed (pthread_cond_signal and pthread_cond_broadcast in POSIX).
如果此线程更改了状态,它可以通知另一个线程(线程1)应唤醒并重新检查其谓词现在可能已更改的谓词(POSIX中的pthread_cond_signal和pthread_cond_broadcast)。
Since there is a shared state, you still need a mutex to protect that shared state and "lock it" when you are modifying or accessing it. 由于存在共享状态,因此在修改或访问共享状态时, 仍需要一个互斥体来保护该共享状态并“锁定”它。
The typical use case of a POSIX condition is a shared queue. POSIX条件的典型用例是共享队列。 A consumer wishes to "consumes" data items from the queue and, to do so, must wait on a boolean predicate [the queue is non-empty].
消费者希望从队列中“消费”数据项,并且这样做必须等待布尔谓词[队列为非空]。 The producer generates data items that it deposits in the shared queue.
生产者生成它存储在共享队列中的数据项。 As it adds items, it should notify any "waiters" that they should recheck.
在添加项目时,它应通知任何“服务员”他们应该重新检查。
Bottom line: conditions are not helpful here. 底线:条件在这里没有帮助。 You don't even need mutexes in your example.
您的示例中甚至不需要互斥体。 And conditions must be used with a mutex anyway (the call to pthread_cond_wait takes as input the address of a mutex to atomically release the lock and sleep on the condition).
而且条件必须始终与互斥锁一起使用(对pthread_cond_wait的调用将输入互斥锁的地址作为输入,以原子方式释放该锁并在条件上休眠)。 mutex are for mutual exclusion .
互斥是互斥的 。 Conditions are meant for signaling .
条件是为了发出信号 。 Two very different purposes.
两个非常不同的目的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.