while (flag == 0) { };where flag is a shared variable. This form of waiting is referred to as busy wait. Busy waiting is expensive in terms of processor usage. Therefore, it is only advisable to use spin block for extremely short waiting periods (less than 200 instructions say). For longer waiting periods it is better to use a process block which suspends the process. A suspended process relinquishes the processor it is on so it can be used for other things. A suspended process will be activated when the condition it is waiting for is met.
semaphore_wait(S); code in the critical section semaphore_signal(S);
task A; begin --Input first data set loop signal(StartB) <=== Invoke task B --Input next data set wait(StartA) <=== wait until task B finishes with the data endloop end A; task B; begin loop wait(StartB) <=== wait for task A to read the data --Process the data signal(StartA) <=== tell task A to continue endloop; end B;
__________ | stack | | | | | | | | \/ | | | | stack | | | | | | | | \/ | | | ... | stack | | | | | | | | \/ | | heap | -----------
task Name is
--specific declarations allowing synchronization and
--communication with other tasks
end;
task body Name is
--the usual local declarations as found in any program
begin
--sequence of statements
end;
task type Name is
--the rest of the definition in the same form as above
end;
A, B, C: Name
alternatively the declarations can be done using pointers
type taskPtr is access Name;
newName: taskPtr := new Name;
task Name is
entry Entry_1(Item: in INTEGER)
end;
task body Name is
--the usual local declarations as found in any program
begin
loop
accept Entry_1(Item: in INTEGER) do
...
end Entry_1
end loop;
end Name;
task body Name is
loop
select
accept Entry_1 (formal parameters) do
...
end Entry_1;
...
or
accept Entry_2 (formal parameters) do
...
end Entry_2;
...
end select;
end loop;
end Name;
when not Full(Buffer) =>
accept Deposit(New_Value) do
task body Name is
loop
select
accept Entry_1 (formal parameters) do
...
end Entry_1;
...
or
accept Entry_2 (formal parameters) do
...
end Entry_2;
or
terminate;
end select;
end loop;
end Name;
task Binary_Semaphore is
entry Wait;
entry Release;
end Binary_Semaphore
task body Binary_Semaphore
begin
loop
accept Wait;
accept Release;
end loop;
end Binary_Semaphore;
Thread ballgame;
...
public void stopbutton()
{
ballgame.suspend();
if (askUser("Do you really want to quit the game? (y/n)"))
ballgame.stop();
else
ballgame.resume();
}
class ManageBuffer
{
private int[100] buffer;
...
public synchronized void deposit(int item) {...}
public synchronized int fetch() {...}
...
}
synchronized(expression) <=== expression evaluates to an object
statement; <=== a single or compound statement