gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:25:48 24 4
gpt4 key购买 nike

我有一个类似下面的函数,其中线程通过使用 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();
}
}
}

在上面的 if 条件下,即 the_compress_thread_is_not_already_running,我如何确定压缩线程没有运行?

void * compress_log (std::string s) 
{

// Compress the file
// ...

}

最佳答案

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

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

另一种方法可能是不断保持压缩线程处于事件状态,但只要没有工作要完成就将其阻塞。可以使用条件变量通知线程开始其工作,一旦完成,恢复阻塞直到下一次通知。

附言您可能希望先关闭文件流,重命名文件,然后在您持有锁的同时重新打开,以便其他线程可以继续登录到新文件,而以前的日志(现在在重命名的文件中)正在被压缩。

关于c++ - 如何知道分离的 std::thread 是否已完成执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54750419/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com