Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is sleeping inside a critical section a concurrency issue?

I would like to understand why is it a concurrency issue if I try to sleep in a critical section, even though I took a lock.

I could be sleeping because say I'm doing I/O.

like image 990
anyuser Avatar asked Sep 13 '25 20:09

anyuser


1 Answers

The issue is basically that while you're sleeping, you're not accomplishing anything. In general, you want to be "in" the critical section for as short of a time as possible. The longer you spend in the critical section, the longer any other thread will have to wait to enter it.

I/O should almost certainly be done outside any critical section as a rule. Just for example, if you're reading some data, you'd want to read the data, then enter the critical section and add the data to some structure so everything else can see it (e.g., add a node with a pointer to that data into a vector), then leave the CS.

There's almost never a good reason to do the I/O itself in a CS -- you'd typically just have a single thread do the I/O, and have a queue (or deque, or whatever) to deal with input to or output from that thread. Adding something to or reading something from the queue is protected by a CS (or perhaps a semaphore, etc.) but happens quickly so one thread can do its thing, then quickly get out of the way so other threads can as well.

like image 68
Jerry Coffin Avatar answered Sep 15 '25 10:09

Jerry Coffin