简体   繁体   English

当std :: lock_guard仍然在作用域内时,使用pthread_create创建线程是否安全?

[英]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: 当线程锁定互斥锁时,可能会发生两件事:

  1. A mutex is unlocked - it becomes locked and the thread execution continues. 互斥锁被解锁-它被锁定并且线程执行继续。
  2. A mutex is already locked - the thread does not continue, but waits until the mutex becomes unlocked. 互斥锁已被锁定-线程不会继续运行,但要等到互斥锁被解锁。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM