c++multithreadingwaitforsingleobject

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


I want the while loop in the thread to run , wait a second, then run again, so on and so on., but this don't seem to work, how would I fix it?

main(){
    bool flag = true;
    pthread = CreateThread(NULL, 0, ThreadFun, this, 0, &ThreadIP);
    
}
ThreadFun(){
    while(flag == true)
        WaitForSingleObject(pthread,1000); 
}

Solution

  • 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

    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: