You are on page 1of 13

INTRODUCTION

A sequential program has a single thread of control. A concurrent program has multiple threads of control allowing it perform multiple computations in parallel and to control multiple external activities which occur at the same time. Interacting, concurrent software components of a system: single machine shared memory interactions multiple machines network interactions

1.1

WHY CONCURRENT PROGRAMMING?


Performance gain from multiprocessing hardware parallelism. Increased application throughput an I/O call need only block one thread. Increased application responsiveness high priority thread for user requests. More appropriate structure for programs which interact with the environment, control multiple activities and handle multiple events.

1.2

MODELS
A model is a simplified representation of the real world. Focus on an aspect of interest - concurrency model animation to visualize a behavior mechanical verification of properties (safety & progress) Labelled Transition Systems LTS textual Finite state processes (FSP) graphical

CONCURRENT EXECUTION
1.1

MODELLING CONCURRENCY
A process progresses by submitting a sequence of instructions to a processor for execution. If the computer has multiple processors then instructions can be executed at the same time. This is sometime referred to as parallel or real concurrent execution. However, it is usual to have more active processes than processors. In this case, the available processors are switched between processes.

1.2

DEFINITIONS

A B
Time

The above figure depicts this switching for the case of a single processor supporting two processes, A and B. The solid line represent instructions from a process being executed on the processor. With a single processor, each process make progress, but as depicted in the figure above, instructions from only one process at a time can be executed. The switching between processes occurs voluntarily or in response to interrupts. Interrupts signal external events such as the completion of a I/O operation or a clock tick to the processor. As can be seen from the previous diagram, processor switching does not affect the order of instructions executed by each process. The processor executes a sequence of instructions which is an interleaving of the instruction sequence from each individual process. This form of concurrent execution using interleaving is sometimes referred to as pseudo-concurrent execution since instructions from different processes are not executed at the same time but are interleaved.

Both concurrency and parallelism require controlled access to shared resources . We use the terms parallel and concurrent interchangeably and generally do not distinguish between real and pseudoconcurrent execution. Concurrency - Logically simultaneous processing. Does not imply multiple processing elements (PEs). Requires interleaved execution on a single PE. Parallelism - Physically simultaneous processing. Involves multiple PEs and/or independent device operations.

How to model concurrency ? arbitrary relative order of actions from different processes (interleaving but preservation of each process order ) provides a general model independent of scheduling (asynchronous model of execution)

2 2.1

PARALLEL COMPOSITION ACTION INTERLEAVING

ITCH = (scratch->STOP). CONVERSE = (think->talk->STOP). ||CONVERSE_ITCH = (ITCH || CONVERSE).

Possible traces as a result of action interleaving.

Algebraic laws : Commutative: (P||Q) = (Q||P) Associative: (P||(Q||R)) = ((P||Q)||R) = (P||Q||R).

3 3.1

MODELLING INTERACTIONS SHARED ACTIONS

If processes in a composition have actions in common, these actions are said to be shared. Shared

actions are the way that process interaction is modeled, while unshared actions may be arbitrarily interleaved, a shared action must be executed at the same time by all processes that participate in the shared action.
MAKER = (make->ready->MAKER). USER = (ready->use->USER). ||MAKER_USER = (MAKER || USER).

3 (distinct actions) (3+1) = 4 states ?? MAKER synchronizes with USER when ready.

3.2

HANDSHAKE

A handshake is an action acknowledged by another:

MAKERv2 = (make->ready->used->MAKERv2). USERv2 = (ready->use->used ->USERv2). ||MAKER_USERv2 = (MAKERv2 || USERv2).

4 (distinct actions) 4 states ?? Interaction constrains the overall behavior.

3.3

MULTIPLE PROCESSES

Multi-party synchronization
MAKE_A = (makeA->ready->used->MAKE_A). MAKE_B = (makeB->ready->used->MAKE_B). ASSEMBLE = (ready->assemble->used->ASSEMBLE). ||FACTORY = (MAKE_A || MAKE_B || ASSEMBLE).

COMPOSITE PROCESSES
||MAKERS = (MAKE_A || MAKE_B). -------------(1) ||FACTORY = (MAKERS || ASSEMBLE).-----------(2)

A composite process is a parallel composition of primitive processes. These composite processes can be used in the definition of further compositions.

Substituting (1) in (2) and applying commutative and associative laws for parallel composition gives;
||FACTORY = (MAKE_A || MAKE_B || ASSEMBLE).

Original definition of ||FACTORY in terms of primitive processes

4.1

PROCESS INSTANCES AND LABELING


SWITCH = (on->off->SWITCH). ||TWO_SWITCH = (a:SWITCH || b:SWITCH).

a:P prefixes each action label in the alphabet of P with a. Two instances of a switch process:

Array of instances
||SWITCHES(N=3) = (forall[i:1..N] s[i]:SWITCH). Or ||SWITCHES(N=3) = (s[i:1..N]:SWITCH).

4.2

PROCESS LABELLING BY A SET OF PREFIX LABELS FOR SHARED RESOURCES

{a1,..,ax}::P replaces every action label n in the alphabet of P with the labels a1.n,,ax.n. Further, every transition (n->X) in the definition of P is replaced with the transitions ({a1.n,,ax.n} ->X). Process prefixing is useful for modeling shared resources
RESOURCE = (acquire->release->RESOURCE). USER = (acquire->use->release->USER). ||RESOURCE_SHARE = (a:USER || b:USER || {a,b}::RESOURCE).

The model ensure that the user that acquires the resource is the one to release it?

4.3

ACTION RELABELLING FOR SHARED ACTIONS


Relabeling functions are applied to processes to change the names of action labels. The general form of the relabeling function is: /{newlabel_1/oldlabel_1, newlabel_n/oldlabel_n}.(Note that both newlabel and oldlabel can be sets of labels. Relabeling to ensure that composed processes synchronize on particular actions.

CLIENT = (call->wait->continue->CLIENT). SERVER = (request->service->reply->SERVER). ||CLIENT_SERVER = (CLIENT || SERVER)/{call/request, reply/wait}.

Without action relabeling Without action relabeling

4.4

ACTION RELABELING PREFIX LABELS

Alternative formulation using qualified or prefix labels


SERVERv2 = (accept.request ->service-> accept.reply->SERVERv2). CLIENTv2 = (call.request->call.reply->continue->CLIENTv2). ||CLIENT_SERVERv2 = (CLIENTv2 || SERVERv2)/{call/accept}.

Relabeling functions are applied to processes and change the names of action labels. This is usually done to ensure that composed processes synchronize on the correct actions.

SHARED OBJECTS AND MUTUAL EXCLUSION


Issues involved in interleaving Issues involved in constructing concurrent programs in which threads interact to communicate and cooperate.

INTERFERENCE
After the East and West threads have each incremented its counter 20 times, the shared counter is not 40 (less than 40). Counter increments have been lost. Why? The simple model of interleaving is insufficient to resolve complexities in constructing concurrent programs Java method activations are not atomic - thread objects East and West may be executing the code for the increment method at the same time they may interleave their read and write actions.

CHECKING FOR ERRORS


1. ANIMATION - Check the trace for errors 2. EXHAUSTIVE ANALYSIS - Compose the model with a TEST process which sums the counter for this example and checks against the shared Counter value. (ERROR is a predefined state in FSP with number -1 in LTS)

INTERFERENCE AND MUTUAL EXCLUSION

Destructive update, caused by the arbitrary interleaving of read and write actions is termed Interference. Interference bugs are extremely difficult to locate. The general solution is to give methods mutually exclusive access to shared objects. Mutual exclusion can be modeled as atomic actions.

MUTUAL EXCLUSIONS IN JAVA

Concurrent activations of a method in Java can be made mutually exclusive by prefixing the method with the keyword synchronized, which uses a lock on the object.

4.1

JAVA SYNCHRONIZED METHOD

Java associates a lock with every object. The Java compiler inserts code to acquire the lock before executing the body of the synchronized method and code to release the lock before the method returns. Concurrent threads are blocked until the lock is released.

4.2

JAVA SYNCHRONIZED STATEMENT

Access to an object may also be made mutually exclusive by using the synchronized statement:
synchronized(people) {people.increment();}

To ensure mutually exclusive access to an object, all object methods should be synchronized.

4.3

MODELING MUTUAL EXCLUSION

To add locking to our model, define a LOCK, compose it with the shared ACTION and modify the alphabet set :
LOCK = (acquire->release->LOCK). ||LOCKVAR = (LOCK || VAR). set VarAlpha = {value.{read[T],write[T],acquire, release}}

4.4

ABSTRACTION USING ACTION HIDING

To model shared objects directly in terms of their synchronized methods, we can abstract the details by hiding. The general form of a hiding expression is /{set of labels to be hidden}. Sometimes it is more convenient to state the set of action labels, which are visible and hide all other labels. This is expressed by @{set of visible labels }. Hiding expressions can be applied to both primitive and composite processes but are generally used in defining composites.
SEMA = (up -> down -> SEMA). ||SEMA2 = (SEMA||SEMA).

||SEMA2 = ( SEMA/{mid/down} || SEMA/{mid/up} ).

Here, the down action of the first SEMA and the up action of the second SEMA has been relabeled by mid for synchronization of the composite.

||SEMA2 = ( SEMA/{mid/down} || SEMA/{mid/up} )\{mid}.

Now, the mid action is made a silent action. By convention, all the silent actions are labeled, as tau . (even if no. of silent actions are more than one)

||SEMA2 = ( SEMA/{mid/down} || SEMA/{mid/up} )@{up,down}.

Produces the same result as above. @ specifies the visible actions.

DEADLOCK
No further progress

1
1. 2. 3. 4.

FOUR NECESSARY AND SUFFICIENT CONDITIONS


Serially reusable resources Incremental acquisition No pre-emption Wait-for cycle

1.1

Serially reusable resources

The processes involved share resources which they use under mutual exclusion. When one thread is accessing a resource, other will not (synchronized keyword). Should code to avoid mutual exclusive state.

1.2

Incremental acquisition

Processes hold on to resources already allocated to them while waiting to acquire additional resources.

While T1 is accessing R1, T2 and T3 cannot access R1.

1.3

No pre-emption

Once acquired by a process, resources cannot be pre-empted (forcibly withdrawn) but are only released voluntarily. This avoided by Java's Thread.interrupt() which can force T1 to withdraw R1

1.4

Wait-for cycle (Circular wait)

A circular chain (or cycle) of processes exists such that each process holds a resource which its successor in the cycle is waiting to acquire. T1 is holding R1 and is waiting to access R2. At that point T2 is holding R2 and waiting to access R1 which is already held by T1. T1 does not release R1 unless he has acquired R2

2 DEADLOCK ANALYSIS 2.1


PRIMITIVE PROCESSES
Deadlocked state is one with no outgoing transitions STOP process in FSP

2.2

AVOID DEADLOCK
1. ACQUIRE RESOURCES IN A PREDEFINED ORDER
RESOURCE = (get->put->RESOURCE). P = (printer.get->scanner.get->copy ->printer.put->scanner.put -> P). Q = (scanner.get->printer.get->copy ->scanner.put->printer.put -> Q). ||SYS = (p:P||q:Q||{p,q}::printer:RESOURCE||{p,q}::scanner:RESOURCE).

Follow the example of two machines trying to access a shared printer and a scanner

???

This denies the second deadlock of incremental acquisition. 2. SET A TIMEOUT ON WAITING FOR THE SECOND RESOURCE If the resource has not been acquired within the timeout period then the first resource is released and the process starts a fresh
RESOURCE = (get->put->RESOURCE). P = (printer.get->scanner.get->copy ->printer.put->scanner.put -> P | timeout -> printer.put -> P). Q = (scanner.get->printer.get->copy ->scanner.put->printer.put -> Q

| timeout -> scanner.put -> Q). ??? ||SYS = (p:P||q:Q||{p,q}::printer:RESOURCE||{p,q}::scanner:RESOURCE).

The solution can be implemented in Java using a timed wait. However, it is not a good solution as both processes can automatically acquired the first resource, time out and then repeat this cycle without making any progress towards accomplishing the next (copy) action 3. AVOID WAIT-FOR CYCLE Deadlock occurs where all the philosophers pick up the fork in right and wait for the fork held by the neighbor in left. Wait-for cycle. While deadlock can be easily detected in a model, it is not so apparent in the running program which corresponds to that model. In translating the (Dining Philosophers) model into an implementation, we must consider which processes in the model will be represented by passive objects (monitors) and which by active objects (threads). Forks are the passive entities monitors Philosophers are the active entities threads in the system. Deadlock can be avoided by ensuring that a wait-for cycle cannot exist. How? Introduce an asymmetry into our definition of philosophers. Use the identity, i of a philosopher to make even numbered philosophers get their left forks first, odd their right first. blocked threads guarded blocks

SAFETY AND LIVELINESS PROPERTIES


Property - an attribute of a program that is true for every possible execution of that program 2 categories of properties I.) Safety asserts that nothing bad happens during execution program not reaching a bad state II.) Liveness asserts that something good eventually happens. program eventually reaching a good state

SAFETY
Asserts that nothing bad happens during execution program not reaching a bad state STOP or deadlocked state (no outgoing transitions) ERROR process (-1) to detect erroneous behavior process should not respond to second command, unless it has responded to the first ERROR condition states what is not required(exceptions) In sequential programs, the most important safety property is that the final state is correct. For concurrent programs, important safety properties are mutual exclusion and the absence of deadlock.

1.1

SAFETY PROPERTIES
Safety properties are deterministic primitive processes which contains no silent (tau) transitions (no hiding). Safety property processes are denoted by the keyword property. Informally, a property process specifies a set of acceptable behaviors for the system it is composed with. A system S will satisfy a property P if S can only generate sequences of actions (traces) which when restricted to the alphabet of P, are acceptable to P. For example, the following property specifies that only behavior in which knock occurs before enter is acceptable.
property POLITE = (knock->enter->POLITE).

The systems specified below would generate property violations:

HESITANT = (knock->knock->enter->HESITANT). IMPATIENT = (enter -> IMPATIENT). ||SysA = (HESITANT || POLITE). ||SysB = (IMPATIENT || POLITE).

Property processes do not constraint the operation of the systems they are composed with. They are compiled into "image" LTS, which accept all possible interleaving of their alphabets. However, violating sequences of actions lead to an error state (represented as -1) as shown in the LTS for POLITE. ERROR state brings the system to a halt. Does not engage any further actions. How can we specify that some action, disaster, never occurs? Define the property;
property CALM = STOP + {disaster}.

A safety property must be specified so as to include all the acceptable, valid behaviors in its alphabet.

LIVELINESS
Liveliness property for a sequence program is termination, but concurrent programs, termination doesn't frequently occur liveness issues relating to resource access: are process requests for shared resources eventually granted Asserts that something good eventually happens. An action is eventually executed starvation a concurrent programming situation in which an action is never executed. A progress property asserts that it is always the case that an action is eventually executed. Progress is the opposite of starvation.

2.1

PROGRESS PROPERTIES
Fair Choice : If a choice over a set of transitions is executed infinitely often, then every transition in the set will be executed infinitely often. If the coin were tossed an infinite number of times, we would expect that heads would be chosen infinitely often and that tails would be chosen infinitely often.
progress P = {a1,a2..an}

defines a progress property P which asserts that in an infinite execution of a target system, at least one of the actions a1,a2..an will be executed infinitely often. In other words, a progress property asserts that at any stage of execution one of the actions in

the progress set will eventually occur. The liveness requirement for coin tossing can now be expressed as:
progress HEADS = {heads} progress TAILS = {tails}

Example of two coins where one coin is fair, and other is a trick coin with two heads. Action pick involves in picking a coin. If the trick coin is picked only head occurs. Therefore, property progress TAILS is violated. But property progress HEAD is achieved. If progress HEADSorTail = {heads,tails} was the progress property, this property will not be violated since only one of the actions in the progress set need be executed infinitely often to satisfy the property.

2.2

PROGRESS ANALYSIS
A terminal set of states is one in which every state is reachable from every other state in the set via one or more transitions, and there is no transition from within the set to any state outside the set. Terminal sets for two coins.

An execution of a system represented by a finite set of states can only be infinite if some of the states are visited infinitely often. The states that are visited infinitely often in an execution must form a terminal set. Given fair choice, each terminal set of states represents an execution in which each transition in the set is executed infinitely often. Since there is no transition out of a terminal set, any action that is not used in all terminal sets cannot occur infinitely often in all executions of the system. Checking that a progress property holds is now simply checking that in each terminal set, at least one of the actions in the progress set occurs as a transition. Conversely, a progress property is violated if analysis finds a terminal set of states in which none of the progress set actions appear. For the TAILS property, this terminal set is the set of states {1, 2} in which the action tails does not occur. The output gives the shortest execution path to the root of the terminal set and lists the actions that do appear in the set. Since there is no transition out of a terminal set, any action that is not used in the set cannot occur infinitely often in all executions of the system - and hence represents a potential progress violation! A progress property is violated if analysis finds a terminal set of states in which none of the progress set actions appear. If no progress properties are specified, LTSA performs progress analysis using a default property. This property asserts that for every action in the alphabet of the target system, given fair choice, that action will be executed infinitely often. All systems in which the states occur inside a single terminal set satisfy the default progress property. Here, since pick is not infinitely executed, this as well violates the progress property

2.3

ACTION PRIORITY
Describes the scheduling properties

High Priority Operator (<<) ||C = (P||Q) <<{a1,...,an} specifies a composition in which the actions a1,...,an have higher priority than any other action in the alphabet of P||Q including the silent action tau. In any choice in this system which has one or more of the actions a1,...,an labeling a transition, the transitions labeled with lower priority actions are discarded. Low Priority Operator (>>) ||C = (P||Q)>>{a1 ,...,an } specifies a composition in which the actions a1,...,an have lower priority than any other action in the alphabet of P||Q including the silent action tau. In any choice in this system which has one or more transitions not labeled by a1,...,an, the transitions labeled by a1,...,an are discarded.
NORMAL =(work->play->NORMAL|sleep->play->NORMAL).

||HIGH =(NORMAL)<<{work}.

||LOW

=(NORMAL)>>{work}.

MODEL BASED DESIGN


1

SAFETY PROPERTIES
Safety checks are compositional. If there is no violation at a subsystem level, then there cannot be a violation when the subsystem is composed with other subsystems. This is because, if the ERROR state of a particular safety property is unreachable in the LTS of the subsystem, it remains unreachable in any subsequent parallel composition which includes the subsystem. Hence... Safety properties should be composed with the appropriate system or subsystem to which the property refers. In order that the property can check the actions in its alphabet, these actions must not be hidden in the system.

PROGRESS PROPERTIES

Progress checks are not compositional. Even if there is no violation at a subsystem level, there may still be a violation when the subsystem is composed with other subsystems. This is because an action in the subsystem may satisfy progress yet be unreachable when the subsystem is composed with other subsystems which constrain its behavior. Hence... Progress checks should be conducted on the complete target system after satisfactory completion of the safety checks.

MODEL INTERPRETATION
Models can be used to indicate system sensitivities. If it is possible that erroneous situations detected in the model may occur in the implemented system, then the model should be revised to find a design which ensures that those violations are avoided. However, if it is considered that the real system will not exhibit this behavior, then no further model revisions are necessary. Model interpretation and correspondence to the implementation are important in determining the relevance and adequacy of the model design and its analysis. Design architecture describes the gross organization and global structure of the system in terms of its constituent components. Consider that the models for analysis and the implementation should be considered as elaborated views of this basic design structure.

3.1
1. 2. 3. 4.

MODEL JAVA
identify the main active entities - to be implemented as threads identify the main (shared) passive entities - to be implemented as monitors reacts to events identify the interactive display environment- to be implemented as associated classes structure the classes as a class diagram

You might also like