【发布时间】:2019-02-15 12:03:30
【问题描述】:
我有一个类似下面的函数,其中线程通过使用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);
}
【问题讨论】:
-
你为什么使用
pthread_create和std::mutex而不是std::thread?顺便说一句,您的比赛条件超过_compress_thread -
"是否将锁定应用于新线程" 仅当您的代码中有 UB 时。否则保证互斥量一次只能被一个线程锁定。
-
@Slava,请原谅我的无知,但什么是“UB”?所以新线程不会有这个锁。
-
@Slava,为了解决
_compress_thread上的竞争条件,我更新了上面的代码。你能检查一下并告诉我是否可以吗?
标签: c++ multithreading pthreads