使用互斥量和条件变量而不是信号量在 C++14 中打印从 1 到 10 的数字?
Using mutex and conditional variable instead of semaphore to print numbers from 1 to 10 in c++14?
我正在尝试使用两个线程打印从 1 到 n 的数字。一个用于递增,另一个用于打印。由于在新的 C++ 中没有标准库信号量 class,我使用互斥锁和条件变量来模拟二进制信号量来完成这项工作。下面的代码不打印任何值,但 "main is here!"。我多次检查我的代码,但找不到解决方案。我在这里错过了什么吗?
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex m;
condition_variable cv;
int v=0;
void modify()
{
while(v<10)
{
lock_guard<mutex> lock(m);
v=v+1;
cv.notify_all();
}
}
void print()
{
while(v<10)
{
unique_lock<mutex> lock(m);
cv.wait(lock);
cout<<v<<" ";
lock.unlock();
cv.notify_all();
}
}
int main() {
thread t1(modify);
thread t2(print);
t1.join();
t2.join();
cout<<endl<<"main is here!"<<endl;
return 0;
}
信号量的实现非常简单,可以在这里找到:
C++0x has no semaphores? How to synchronize threads?
但其实你并不需要
您的代码的问题是 modify
函数不等待 print
函数。查看我对代码的更改:
void modify()
{
// Fix #1: Any access to v should be done inside lock
unique_lock<mutex> lock(m);
while(v<10)
{
v=v+1;
cv.notify_all();
// Fix #2: wait for print function
cv.wait(lock);
}
}
void print()
{
// See Fix #1
unique_lock<mutex> lock(m);
while(v<10)
{
cv.wait(lock);
cout << v << " ";
// Fix #3: no need to unlock here
cv.notify_all();
}
}
我正在尝试使用两个线程打印从 1 到 n 的数字。一个用于递增,另一个用于打印。由于在新的 C++ 中没有标准库信号量 class,我使用互斥锁和条件变量来模拟二进制信号量来完成这项工作。下面的代码不打印任何值,但 "main is here!"。我多次检查我的代码,但找不到解决方案。我在这里错过了什么吗?
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
mutex m;
condition_variable cv;
int v=0;
void modify()
{
while(v<10)
{
lock_guard<mutex> lock(m);
v=v+1;
cv.notify_all();
}
}
void print()
{
while(v<10)
{
unique_lock<mutex> lock(m);
cv.wait(lock);
cout<<v<<" ";
lock.unlock();
cv.notify_all();
}
}
int main() {
thread t1(modify);
thread t2(print);
t1.join();
t2.join();
cout<<endl<<"main is here!"<<endl;
return 0;
}
信号量的实现非常简单,可以在这里找到: C++0x has no semaphores? How to synchronize threads?
但其实你并不需要
您的代码的问题是 modify
函数不等待 print
函数。查看我对代码的更改:
void modify()
{
// Fix #1: Any access to v should be done inside lock
unique_lock<mutex> lock(m);
while(v<10)
{
v=v+1;
cv.notify_all();
// Fix #2: wait for print function
cv.wait(lock);
}
}
void print()
{
// See Fix #1
unique_lock<mutex> lock(m);
while(v<10)
{
cv.wait(lock);
cout << v << " ";
// Fix #3: no need to unlock here
cv.notify_all();
}
}