Delayed Start of a Thread in C++ 11

std::thread does not start immediately as expected (c++11)

You are not measuring what you think you are measuring here:

start= std::chrono::system_clock::now();
auto Thread = std::thread([](){std::cout<<"Excuting thread"<<std::endl;});
stop = std::chrono::system_clock::now();

The stop timestamp only gives you an upper bound on how long it takes main to spawn that thread and it actually tells you nothing about when that thread will start doing any actual work (for that you would need to take a timestamp inside the thread).

Also, system_clock is not the best clock for such measurements on most platforms, you should use steady_clock by default and resort to high_resolution_clock if that one doesn't give you enough precision (but note that you will have to deal with the non-monotonic nature of that clock by yourself then, which can easily mess up the gained precision for you).

As was mentioned already in the comments, spawning a new thread (and thus also constructing a new std::thread) is a very complex and time-consuming operation. If you need high responsiveness, what you want to do is spawn a couple of threads during startup of your program and then have them wait on a std::condition_variable that will get signalled as soon as work for them becomes available. That way you can be sure that on an otherwise idle system a thread will start processing the work that was assigned to him very quickly (immediately is not possible on most systems due to how the operating system schedules threads, but the delay should be well under a millisecond).

Creating a delay() function using thread (C++)

The std::this_thread::sleep_for() function only causes the calling thread to sleep.

In your case, you are creating a second thread which sleeps while the thread running main() continues executing.

It should look more like this:

void delay(int delaytime)
{
std::this_thread::sleep_for(std::chrono::milliseconds(delaytime));
}

Does a thread start immediately

A join method essentially says "block execution until the thread completes at which time return from my call to join".

If a thread has already run and exited by the time you call join it will simply immediately return. If the thread is still running then your call to join will be blocked until the thread completes at which point it will return. In neither of these situations will there be a failure.

The following is the exact text of the documentation for the join function:

The function returns when the thread execution has completed.

This synchronizes the moment this function returns with the completion
of all the operations in the thread: This blocks the execution of the
thread that calls this function until the function called on
construction returns (if it hasn't yet).

http://www.cplusplus.com/reference/thread/thread/join/

How to let a thread wait itself out without using Sleep()?

While the other answer is a possible way to do it, my answer will mostly answer from a different angle trying to see what could be wrong with your code...

Well, if you don't care to wait up to one second when flag is set to false and you want a delay of at least 1000 ms, then a loop with Sleep could work but you need

  • an atomic variable (for ex. std::atomic)
  • or function (for ex. InterlockedCompareExchange)
  • or a MemoryBarrier
  • or some other mean of synchronisation to check the flag.

Without proper synchronisation, there is no guarantee that the compiler would read the value from memory and not the cache or a register.

Also using Sleep or similar function from a UI thread would also be suspicious.

For a console application, you could wait some time in the main thread if the purpose of you application is really to works for a given duration. But usually, you probably want to wait until processing is completed. In most cases, you should usually wait that threads you have started have completed.

Another problem with Sleep function is that the thread always has to wake up every few seconds even if there is nothing to do. This can be bad if you want to optimize battery usage. However, on the other hand having a relatively long timeout on function that wait on some signal (handle) might make your code a bit more robust against missed wakeup if your code has some bugs in it.

You also need a delay in some cases where you don't really have anything to wait on but you need to pull some data at regular interval.

A large timeout could also be useful as a kind of watch dog timer. For example, if you expect to have something to do and receive nothing for an extended period, you could somehow report a warning so that user could check if something is not working properly.

I highly recommand you to read a book on multithreading like Concurrency in Action before writing multithread code code.

Without proper understanding of multithreading, it is almost 100% certain that anyone code is bugged. You need to properly understand the C++ memory model (https://en.cppreference.com/w/cpp/language/memory_model) to write correct code.

A thread waiting on itself make no sense. When you wait a thread, you are waiting that it has terminated and obviously if it has terminated, then it cannot be executing your code. You main thread should wait for the background thread to terminate.

I also usually recommand to use C++ threading function over the API as they:

  • Make your code portable to other system.
  • Are usually higher level construct (std::async, std::future, std::condition_variable...) than corresponding Win32 API code.

How to run function after delay asynchronously in C++

template <typename F, typename... Args>
auto timed_run(const uint64_t delay_ms, F&& function, Args&&... args) {
std::packaged_task<void()> task([=]() {
std::this_thread::sleep_for(std::chrono::milliseconds(delay_ms));
function(args...);
});

auto future = task.get_future();
std::thread(std::move(task)).detach();

return future;
}


Related Topics



Leave a reply



Submit