简体   繁体   中英

How to know whether detached std::thread has finished its execution?

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.

When the current file size increases the max size, then I create an independent thread that compresses the file and should terminate.

If the log file is big in size (say ~500MB), it takes around 25+ seconds to compress. I detach the compress thread since no other thread (or main) wants to wait for this thread to finish.

But I need to know that the compress thread is not running before the execution of following line:

_compress_thread(compress_log, _logfile).detach();

Sample code snippet:

    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();
            }
        }
    }

In the above if condition ie the_compress_thread_is_not_already_running , how can I be sure that the compress thread is not running?

void * compress_log (std::string s) 
{

    // Compress the file
    // ...

}

It is not possible to detect whether a detached thread of execution has terminated.

If you for some reason need to guarantee that at most one thread is compressing simultaneously, then a simple solution is to use std::async . It returns a future object. You can query the future object whether the associated callback has finished. Same effect can be achieved in a less strucuted way using a detached thread by modifying a shared variable at the end of the function (note that shared access must be synchronised).

Another approach could be to constantly keep alive a compression thread, but block it as long as there is no work to be done. The thread can be notified using a condition variable to start its work and once finished, resume blocking until next notification.

PS You might want to first close the file stream, rename the file, and reopen while you hold the lock so that other threads may keep logging into a fresh file while the previous logs - now in the renamed file - are being compressed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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