Search code examples
cthread-safetypthreadssleep

Does sleep() system call have any drawbacks?


So my aim is to execute a piece of code handled by a thread (let's say thread 1 using POSIX threads) while cancelling a different thread (thread 2) executing it's respective task. Thread 1 is initiated when a particular event occurs (time based event - in my case 60 seconds).

To achieve this, I was using the sleep() function. But I am told by my mentor that it's a bad practice to use sleep in a multithreaded program. I wasn't able to make sense of his reasoning. So hence I decided to escape here.

If my problem seems too vague, mentioning any drawbacks of sleep() would be appreciated.


Solution

  • There are synchronization primitives that allow a thread to wait for another thread (e.g. mutexes, semaphores, condition variables). sleep() will also have your thread wait, but you either sleep for an unnecessary long time (that might not be enough in case the other thread takes longer) or you'd have to check if the other thread is finished anyway (which you'd need to guard with atomic variables or mutexes anyway).

    So for thread synchronization, sleep isn't enough and complicates (+slows down) everything.