如何知道分离的std :: thread是否已完成执行?

问题描述 投票:2回答:1

我有一个类似下面的函数,其中线程通过使用std :: lock_guard互斥锁获取锁并通过ofstream写入文件。

当当前文件大小增加最大大小时,我创建一个压缩文件的独立线程并终止。

如果日志文件很大(比如说~500MB),压缩大约需要25秒以上。我分离压缩线程,因为没有其他线程(或主要)想要等待此线程完成。

但我需要知道压缩线程在执行以下行之前没有运行:

_compress_thread(compress_log, _logfile).detach();

示例代码段:

    void 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 (the_compress_thread_is_not_already_running) //pseudo code
            {
                _compress_thread(compress_log, _logfile).detach();
            }
        }
    }

在上面的qazxsw poi条件i.s. qazxsw poi,我怎么能确定压缩线程没有运行?

if
c++ multithreading stdthread
1个回答
5
投票

无法检测分离的执行线程是否已终止。

如果由于某种原因需要保证最多只有一个线程同时压缩,那么一个简单的解决方案是使用the_compress_thread_is_not_already_running。它返回一个未来的对象。您可以查询未来对象是否关联的回调已完成。通过修改函数末尾的共享变量,使用分离线程以较少的结构方式可以实现相同的效果(请注意,必须同步共享访问)。

另一种方法可能是不断保持压缩线程,但只要没有工作要做就阻止它。可以使用条件变量通知线程以开始其工作,并且一旦完成,则恢复阻塞直到下一个通知。

附:您可能希望首先关闭文件流,重命名文件,并在保持锁定时重新打开,以便其他线程可以继续登录到新文件,同时压缩先前的日志(现在位于重命名的文件中)。

© www.soinside.com 2019 - 2024. All rights reserved.