【发布时间】:2019-02-25 16:54:37
【问题描述】:
1) 我是 std::thread 的新手,我想知道调用pthread_sigmask() 来阻止@987654322 创建的特定 线程中的一些信号是否是一个好习惯@。
我不希望新线程接收SIGTERM、SIGHUP等信号,因为主进程已经为这些信号安装了处理程序。
那么,调用pthread_sigmask() 来阻止std::thread 创建的线程中的一些信号是一种好习惯吗?
2) 另外,我相信pthread_sigmask(SIG_BLOCK, &mask, NULL) 的效果只适用于使用创建的线程
std::thread(&Log::rotate_log, this, _logfile, _max_files, _compress).detach();
并调用rotate_log() 作为启动函数。
并且pthread_sigmask(SIG_BLOCK, &mask, NULL)的效果将不适用于调用std::thread(&Log::rotate_log, this, _logfile, _max_files, _compress).detach()的线程。
我的理解正确吗?
void rotate_log (std::string logfile, uint32_t max_files, bool compress)
{
sigset_t mask;
sigemptyset (&mask);
sigaddset (&mask, SIGTERM);
sigaddset (&mask, SIGHUP);
pthread_sigmask(SIG_BLOCK, &mask, NULL);
// Do other stuff.
}
void Log::log (std::string message)
{
// Lock using mutex
std::lock_guard<std::mutex> lck(mtx);
_outputFile << message << std::endl;
_outputFile.flush();
_sequence_number++;
_curr_file_size = _outputFile.tellp();
if (_curr_file_size >= max_size) {
// Code to close the file stream, rename the file, and reopen
...
// Create an independent thread to compress the file since
// it takes some time to compress huge files.
if (!_log_compression_on)
{
std::thread(&Log::rotate_log, this, _logfile, _max_files, _compress).detach();
}
}
}
【问题讨论】:
-
这至少会假设 std::thread 是根据 pthread 实现的,但情况可能并非如此。
-
我已经在我的问题中提到了目的是“我不希望新线程接收诸如SIGTERM,SIGHUP等信号,因为主进程已经为这些信号安装了处理程序。”现在,在这种情况下,我想知道上面的例子是否符合这个目的,以及我所做的是否是一个好的做法。
标签: c++ multithreading pthreads signals stdthread