سؤال

In the application I'm writing, I want to take a backup of the data every 24 hours to help prevent the risk of data being lost in case of a file corruption or other failure.

To do this I am using a simple thread like this:

void BackupThread( const std::atomic<bool>& bTerminateFlag )
{
    std::stringstream ssFilePathAndName;

    while( !bTerminateFlag.load() )
    {
         std::this_thread::sleep_for( std::chrono::hours(24) );

         std::time_t std::chrono::system_clock::to_time_t( std::chrono::system_clock::now() );

         ssFilePathAndName << "\\Backup" << "\\BackupFile-" << std::put_time( std::localtime( &t ), "%Y-%m-%d-%H-%M-%S" ) << ".txt";

         // Save the data using our thread-safe Singleton object:
         g_pManager->Save( ssFilePathAndName.str() );

         ssFilePathAndName.str( "" );
         ssFilePathAndName.clear();
    }
}

I then start this using a reference to a member variable of my main application class:

m_backupThread = std::thread( BackupThread, std::cref( m_bBackupTerminateFlag ) );

However, I'm curious about whether this is a bad way (system-resource wise) to be going about this process, because although I have specified that the thread must wait 24 hours before waking, presumably the thread will be revived at various points by the scheduler/OS to check the time condition, and I was concerned about whether this would result in a non-negligible amount of power or CPU time being wasted (considering this will be running on the system constantly for a very long time, and it will not be the only process running on the system).

هل كانت مفيدة؟

المحلول

Sleep() is, typically, an extra entry in an ordered delta-queue in the kernel, so a minimal extra pointer has to be maintained in the container - the cost is indeed negligible. There is no need to give the thread any CPU at all while it is sleeping. That said, such long-delay operations are usually implemented by scheduled tasks or timers, but there's not much in it, overall.

Edit - also easy to test. Write a trivial app that starts 5000 threads that do nothing except Sleep(24 hrs). Run it, check its CPU use. It will be 0.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top