如何用while循环写一个信号等待程序(未接到信号时阻滞,接到信号时继续运行)?
C++的题,老板说涉及Posix和信号量的知识点。
求解答!
使用条件变量std::condition_variable和互斥锁std::mutex mtx,即可实现你的需求
详细参考C++11 多线程编程之条件变量std:: condition_variable、wait()、notify_one()、notify_all()_他人是一面镜子,保持谦虚的态度的博客-CSDN博客_std条件变量
#include<iostream>
using namespace std;
int main()
{
string s;
char c;
while((c=cin.get())!='\n')
s.append(1,c)
cout<<s<<endl;
return 0;
}
类似这样,循环输入,回车跳出循环
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
std::mutex m;
std::condition_variable cv;
std::queue<int> data;
std::atomic_bool processed(false);
std::atomic_bool done(false);
void producer_thread() {
int n = 0;
while (1) {
{
// prepare data for consumer
std::unique_lock<std::mutex> lk(m);
std::cout << "producer: ";
for (int i = 0; i < 5; i++) {
data.push(n);
std::cout << n << " ";
n++;
}
std::cout << '\n';
processed = false;
}
// notify consumer the data is ready for processing
cv.notify_one();
// break the loop if there is no more data to send
if (n >= 20) {
done = true;
break;
}
// wait for the consumer finishing to process the data
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []() -> bool { return processed; });
}
}
}
void consumer_thread() {
while (!done) {
// wait for the consumer preparing the data
{
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []() -> bool { return !data.empty(); });
}
// process the data
{
std::unique_lock<std::mutex> lk(m);
std::cout << "consumer: ";
while (!data.empty()) {
std::cout << data.front() << " ";
data.pop();
}
std::cout << '\n';
}
// notify the producer that the data has been processed
processed = true;
cv.notify_one();
}
}
int main() {
std::thread t1(producer_thread);
std::thread t2(consumer_thread);
t1.join();
t2.join();
return 0;
}
$ g++ -Wall main.cpp -lpthread
$ ./a.out
producer: 0 1 2 3 4
consumer: 0 1 2 3 4
producer: 5 6 7 8 9
consumer: 5 6 7 8 9
producer: 10 11 12 13 14
consumer: 10 11 12 13 14
producer: 15 16 17 18 19
consumer: 15 16 17 18 19