Warm tip: This article is reproduced from serverfault.com, please click

I want to print 1 to11,2 to 22 etc with N parallel processes

发布于 2020-12-05 01:18:39
shared var K = L = 1;
    Process_i
while (TRUE) { 
L:=K; 
K:=K+11;
print_num(L, L+10);
}
  • Explanation:

print_num is a routine to print numbers from L to L+10.

I want to accomplish the following scenario:

  • 1st time prints from 1 to 11
  • 2nd time from 12 to 22
  • 3rd from 23 to 33 etc.

The question states that the parallel execution of this can lead to unwanted results(ask us to provide a scenario that leads to them) and to fix this problem using semaphores(up/down). Has anyone got any clue? Because I'm a bit stuck on this

Questioner
Tsosmi
Viewed
1
lordadmira 2020-12-06 07:04:34

If print_num() executes in a new thread, each call to it is subject to race conditions. For example print_num(12,22) could end up executing before print_num(1,11) and the output would be out of order. Or, two or more executions could be printing to STDOUT simultaneously resulting in jumbled output.

You use a semaphore to control access to a limited resource, in this case STDOUT. You can also use a lock. Basically you need to add some code to prevent print_num from executing out of called order and only one instance of it can access STDOUT at a time. You should also add code to the while loop so that it doesn't iterate until print_num is up and running and has established its place in the execution order.

HTH