[英]Is it safe to create a thread using pthread_create when std::lock_guard is still in scope?
I have a function like following in which threads acquire a lock by using std::lock_guard
mutex and write to the file via ofstream
. 我有一个类似以下的函数,其中线程通过使用std::lock_guard
互斥锁获取锁,并通过ofstream
写入文件。
When the current file size increases the max size, then I want to create an independent thread that should compress the file and should terminate. 当当前文件大小增加最大大小时,我想创建一个独立的线程来压缩文件并终止。
I want to understand the implications of calling pthread_create
when std::lock_guard
is still in scope. 我想了解std::lock_guard
仍在作用域内时调用pthread_create
的含义。
Is it safe? 安全吗? Will the lock be applied to the new thread (I don't intend it to be so) as well? 锁是否也将应用于新线程(我不希望如此)?
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);
}
A mutex works at thread level, it only affects the thread that uses it. 互斥锁在线程级别起作用,它仅影响使用它的线程。 When a thread locks a mutex, two things can happen: 当线程锁定互斥锁时,可能会发生两件事:
Your new thread runs the compress_log()
function, which does not access the mutex at all. 您的新线程将运行compress_log()
函数,该函数根本不会访问互斥量。 Consequently, it will run regardless of whether the mutex is locked or not (the mutex in your case will unlock when log()
exits). 因此,无论互斥锁是否被锁定,它都将运行(在您的情况下,互斥锁将在log()
退出时解锁)。
An unrelated advise: use std::thread
instead of pthread_create
, this way your application becomes more portable: 一个不相关的建议:使用std::thread
而不是pthread_create
,这样您的应用程序将变得更加可移植:
std::thread{ [lf] { compress_log(lf); } }.detach();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.