user3129120
user3129120

Reputation: 113

Why is synchronization in a uniprocessor system necessary?

Why is synchronization in a uniprocessor system necessary? I would like to know a specific case as to why it is necessary. If only one process/thread can access the CPU at one time, when would be a case where synchronization is necessary?

Upvotes: 1

Views: 1274

Answers (2)

nishant_boro
nishant_boro

Reputation: 382

Let me give an example to explain this:

Say we have this pseudocode:

function() {
 a = readVariable() // a is a shared resource / global variable say
 ++a
 writeVariable(a) // store a resource
}

Assume value of a = 10;

Say there are 2 processes: P1 and P2. Say P1 started executing first:

function() {
     a = readVariable() // a = 10
     ++a // a = 11. Say P1 run only upto this statement and context switched to P2 right at this moment
     writeVariable(a)
    }

Now, executing P2 after context switching:

function() {
         a = readVariable() // a = 10. This will still be 10, since we didnt run the last statement before context switching.
         ++a // a = 11
         writeVariable(a) // store 11 to global variable a. Then context switch back to P1

Resuming P1:

function() {
             a = readVariable()
             ++a // a = 11
             writeVariable(a) // P1 will continue executing from this line. Since current value of a is 11. It will store that value to global variable a.
        }

Now, what did we understood from this?: Our function was supposed to increment the value of the global variable a by 1 in every run. But since we context switched P1 to P2 before executing all the instructions, the value of a was never stored and hence this leads to ambigous results. The final value of the global variable a should have been 12, but it turned out to be 11 in our case, which is wrong. Hence, we should make sure that the complete function is executed before context switching.

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881403

Synchronisation in a uni-processor system is to ensure that a resource (for example, a mutex controlling a linked list) is locked to a specific thread of execution even while other threads may run.

While you're correct that only one thread can use the CPU at a time, pre-emptive threading means that a thread itself doesn't control when it's paused so that another can run, the OS does. If you allow threads to control their scheduling, that's known as co-operative threading, and it comes with its own set of problems.

So, since a thread cannot know when it will be switched out in a pre-emptive arena, it will want to lock the resource and ensure no other threads of execution can use that resource until it releases the lock. This could be after thousands of context switches that may have happened in the meantime.

Upvotes: 1

Related Questions