frogatto
frogatto

Reputation: 29285

Block a thread with sleep vs block without sleep

I've created a multi-threaded application using C++ and POSIX threads. In which I should now block a thread (main thread) until a boolean flag is set (becomes true).

I've found two ways to get this done.

If I should follow the first way, why do some people write codes following the second way? If the second way should be used, why should we make current thread to sleep? And what are disadvantages of this way?

Upvotes: 6

Views: 5187

Answers (3)

Alan Stokes
Alan Stokes

Reputation: 18964

The first option (a "busy wait") wastes an entire core for the duration of the wait, preventing other useful work being done and/or wasting energy.

The second option is less wasteful - your waiting thread uses very little CPU and allows other threads to run. But it is still wasteful to keep switching back to the thread to check the flag.

Far better than either would be to use a condition variable, which allows the waiting thread to block without consuming any resources until it is able to proceed.

Upvotes: 12

user35443
user35443

Reputation: 6403

The first way (just the plain while) is wasting resources, specifically the processor time of your process.

When a thread is put into sleep, OS may decide that the processor will be used for different tasks when talking about systems with preemptive multitasking. In theory, if you had as many processors / cores as threads, there would not have to be any difference.

If a solution is good or not depends on the operating system used, and sometimes architecture the program is running on. You should consult your syscall reference to find out more about this.

Upvotes: 3

Colonel Thirty Two
Colonel Thirty Two

Reputation: 26559

while(flag); will cause your thread to use all of its allocated time checking the condition. This wastes a lot of CPU cycles checking something which has likely not changed.

Sleeping for a bit causes the thread to pause and give up the CPU to programs that actually need it.

You shouldn't do either though; you should use a threading library to create a flag object and call its wait function, so that the kernel will pause the thread until the flag is set.

Upvotes: 6

Related Questions