所以我希望能够在C ++中运行线程中处理信号。我写了以下代码
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <chrono>
#include <csignal>
using namespace std;
mutex mtx;
void signal_handle(int signal) {
mtx.lock();
cout << "Signal intercepted by thread " << std::this_thread::get_id()
<< endl;
mtx.unlock();
std::this_thread::sleep_for(std::chrono::seconds(1));
}
void thread_func() {
std::signal(SIGUSR1, signal_handle);
while(true) {
std::this_thread::sleep_for(std::chrono::seconds(2));
mtx.lock();
cout << "Thread number looping " << std::this_thread::get_id() << endl;
mtx.unlock();
}
}
void signalling_func() {
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(3));
std::raise(SIGUSR1);
}
}
int main() {
vector<thread> threads;
for (int i = 0; i < 5; ++i) {
threads.push_back(thread(thread_func));
}
thread(signalling_func).detach();
for (auto& th : threads) {
th.join();
}
return 0;
}
信号永远不会由我创建的任何线程处理。我假设它是由主线程处理的。有什么方法可以表明我自己的线程吗?