gpt4 book ai didi

c++ - 在 std::thread 创建的线程中调用 pthread_sigmask 是一种好习惯吗?

转载 作者:太空狗 更新时间:2023-10-29 23:43:17 25 4
gpt4 key购买 nike

1) 我是 std::thread 的新手,我想知道调用 pthread_sigmask() 是否是一个好习惯阻止由 std::thread 创建的特定 线程中的某些信号.

我不希望新线程接收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();
}
}
}

最佳答案

理论上,即使在具有 POSIX 线程的系统上,std::thread 的实现也可能会创建一个非 POSIX 线程,而 pthread_sigmask 会不适用于此类线程。 (尽管 Maxim Egorushkin's comment 是正确的——您确实应该在创建线程的线程中阻塞信号,并且只解除阻塞那些您希望在新线程上处理的信号,以避免竞争条件。)

我不能代表其他实现,但是 GNU/Linux 实现极不可能发生这样的事情。当然,我也不能对这个实现发表权威意见,但是那里有太多的 C 和 C++ 代码假设用户空间线程(无论是 C、C++ 还是 POSIX)和内核任务(那些东西有 TID)。十年前,人们仍然认为 n:m 线程库是可能的(其中 POSIX 线程的早期 1:m 实现只是一个特例)。

但是今天,程序员从一个线程调用unshare (CLONE_FS) 来为该线程提供一个私有(private)的当前目录,与所有其他线程分开。他们调用 setfscreatecon 并期望这只会影响调用线程。他们甚至直接调用系统调用 setresuidsetresgid 因为他们想避免 glibc 用来将更改传播到所有线程的 setxid 广播(内核不支持的东西)直接地)。所有这些都将在 n:m 线程模型下停止工作。因此 std::thread 和 POSIX 线程必须映射到内核任务,强制执行 1:1 模型。

此外,对于 C 和 C++,只有一个 GNU TLS ABI,这反过来又要求系统中只能有一种类型的线程,使用一个线程指针用于最终到达线程-本地数据。

这就是为什么在 GNU/Linux 上,std::thread 不太可能使用 glibc 提供的 POSIX 线程以外的任何东西。

关于c++ - 在 std::thread 创建的线程中调用 pthread_sigmask 是一种好习惯吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54871085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com