当 std::lock_guard 仍在范围内时,使用 pthread_create 创建线程是否安全?
Is it safe to create a thread using pthread_create when std::lock_guard is still in scope?
我有一个类似下面的函数,其中线程通过使用 std::lock_guard
互斥锁获取锁并通过 ofstream
写入文件。
当当前文件大小增加到最大大小时,我想创建一个独立线程来压缩文件并终止。
我想了解在 std::lock_guard
仍在范围内时调用 pthread_create
的含义。
安全吗?锁也会应用到新线程吗(我不打算这样)?
void log (std::string message)
{
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) {
char *lf = strdup(_logfile.c_str());
// Create an independent thread to compress the file since
// it takes some time to compress huge files.
if (!_compress_thread) {
pthread_create(&_compress_thread, NULL, compress_log, (void *)lf);
}
}
}
void * compress_log (void *arg)
{
pthread_detach(pthread_self());
// Code to compress the file
// ...
{ // Create a scope for lock_gaurd
std::lock_guard<std::mutex> lck(mtx);
_compress_thread = NULL;
}
pthread_exit(NULL);
}
互斥锁在线程级别工作,它只影响使用它的线程。当线程锁定互斥锁时,可能会发生两件事:
- 一个互斥量被解锁 - 它被锁定并且线程继续执行。
- 互斥量已被锁定 - 线程不会继续,而是等待互斥量解锁。
您的新线程 运行 是 compress_log()
函数,它根本不访问互斥锁。因此,无论互斥量是否被锁定,它都会 运行 (当 log()
退出时,你的情况下的互斥量将解锁)。
一条不相关的建议:使用 std::thread
而不是 pthread_create
,这样您的应用程序将变得更加便携:
std::thread{ [lf] { compress_log(lf); } }.detach();
我有一个类似下面的函数,其中线程通过使用 std::lock_guard
互斥锁获取锁并通过 ofstream
写入文件。
当当前文件大小增加到最大大小时,我想创建一个独立线程来压缩文件并终止。
我想了解在 std::lock_guard
仍在范围内时调用 pthread_create
的含义。
安全吗?锁也会应用到新线程吗(我不打算这样)?
void log (std::string message)
{
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) {
char *lf = strdup(_logfile.c_str());
// Create an independent thread to compress the file since
// it takes some time to compress huge files.
if (!_compress_thread) {
pthread_create(&_compress_thread, NULL, compress_log, (void *)lf);
}
}
}
void * compress_log (void *arg)
{
pthread_detach(pthread_self());
// Code to compress the file
// ...
{ // Create a scope for lock_gaurd
std::lock_guard<std::mutex> lck(mtx);
_compress_thread = NULL;
}
pthread_exit(NULL);
}
互斥锁在线程级别工作,它只影响使用它的线程。当线程锁定互斥锁时,可能会发生两件事:
- 一个互斥量被解锁 - 它被锁定并且线程继续执行。
- 互斥量已被锁定 - 线程不会继续,而是等待互斥量解锁。
您的新线程 运行 是 compress_log()
函数,它根本不访问互斥锁。因此,无论互斥量是否被锁定,它都会 运行 (当 log()
退出时,你的情况下的互斥量将解锁)。
一条不相关的建议:使用 std::thread
而不是 pthread_create
,这样您的应用程序将变得更加便携:
std::thread{ [lf] { compress_log(lf); } }.detach();