What exactly is a critical section?
Asked Answered
A

3

7

Just want a little clarity on the this. Imagine I use the windows api of EnterCriticalSection. I call all of them with EnterCriticalSection(&criticalsection);

This is the thread function that is multi threaded

void thread (){

//enter critical section  (part 1)
data
//leave critical section
///more data 1
//entercritical section  (part 2)
//more data 2
//leave critical section 

}

Once a thread enters the critical (part 1), other threads cannot enter that section regardless of whether more data 1 actually has any shared data or not right? Also during that time other threads also cannot enter part 2 of the critical section either.

Acrylyl answered 9/4, 2011 at 19:2 Comment(1)
Hans - not true. Jake asked if a process being in CriticalSection1 would lock both CS1 and CS2. This is false - critical sections are independent. Jake, if you want CS1 to lock both, you'd nest CS2 inside CS1.Delectable
R
10

Critical section is a code chunk. If any thread entered it, no other thread can enter until it's free. If 1 and 2 are different critical sections (i.e. handled by a different semaphore), someone can enter 2 if 1 is occupied.

Rubicund answered 9/4, 2011 at 19:6 Comment(0)
S
3

The rule is simple: only one thread can execute code inside a particular critical section (any portion of code executed between calls to EnterCriticalSection and LeaveCriticalSection on the same instance). From the point of view of the operating system things like portions of code, functions are irrelevant here. The only thing that matters is the number of calls to the mentioned routines. Whenever a situation happens that some thread called EnterCriticalSection more times than LeaveCriticalSection on a particular critical section object, it is said to be "inside that critical section".

That said you can have multiple critical sections created and they are enforced independently. So one critical section is never affecting another critical section. Different critical sections are created using separate calls to the constructor.

Sinistrous answered 9/4, 2011 at 19:7 Comment(0)
H
3

See this:

Consider a variable

int k

two threads are operating on k with this statement

k+=100;

Now assume k equals to 0. The first thread starts to read k, find k=0, then add k by 100. Then the second thread starts to read k before the 1st thread write k=100 back. Then the second thread will assume k=0 and add it by 100 and finally after two threads join k=100 not expected 200. This is the reason we set k+=100 a critical section.

Hesper answered 9/4, 2011 at 19:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.