e01.org

join-pattern

Join-patterns provides a way to write concurrent, parallel and distributed computer programs by message passing. Compared to the use of threads and locks, this is a high level programming model using communication constructs model to abstract the complexity of concurrent environment and to allow scalability. Its focus is on the execution of a chord between messages atomically consumed from a group of channels. This template is based on join-calculus and uses pattern matching. Concretely, this is done by allowing the join definition of several functions and/or channels by matching concurrent call and messages patterns. It is a type of concurrency pattern because it makes easier and more flexible for these entities to communicate and deal with the multi-threaded programming paradigm.

Join-patterns provides a way to write concurrent, parallel and distributed computer programs by message passing. Compared to the use of threads and locks, this is a high level programming model using communication constructs model to abstract the complexity of concurrent environment and to allow scalability. Its focus is on the execution of a chord between messages atomically consumed from a group of channels. This template is based on join-calculus and uses pattern matching. Concretely, this is done by allowing the join definition of several functions and/or channels by matching concurrent call and messages patterns. It is a type of concurrency pattern because it makes easier and more flexible for these entities to communicate and deal with the multi-threaded programming paradigm. j.When(a1).And(a2). ... .And(an).Do(d) More precisely, when a message matches with a chain of linked patterns causes its handler to run (in a new thread if it's in asynchronous context) otherwise the message is queued until one of its patterns is enabled; if there are several matches, an unspecified pattern is selected. Join-pattern is defined by a set of pi-calculus channels that supports two different operations, sending and receiving, we need two join calculus names to implement it: a channel name for sending (a message), and a function name for receiving a value (a request). The meaning of the join definition is that a call to returns a value that was sent on a channel . Each time functions are concurrently, triggers the return process and synchronizes with other joins. J ::= //join patterns | x //message send pattern | x(y) //function call pattern | J | JBIS //synchronization In most of cases, the order of synchronous calls is not guaranteed for performance reasons. Finally, during the match the messages available in the queue could be stolen by some intervening thread; indeed, the awakened thread may have to wait again. using Microsoft.Research.Joins; class SymmetricBarrier { public readonly Synchronous.Channel Arrive; public SymmetricBarrier(int n) { // Create j and init channels (elided) JoinPattern pat = j.When(Arrive); for (int i = 1; i { }); } } Dining philosophers problem using Microsoft.Research.Joins; Join j = Join.Create(); Synchronous.Channel[] hungry; Asynchronous.Channel[] chopstick; j.Init(out hungry, n); j.Init(out chopstick, n); for (int i = 0; i { eat(); left(); right(); // replace chopsticks }); } Mutual exclusion using Microsoft.Research.Joins; class Lock { public readonly Synchronous.Channel Acquire; public readonly Asynchronous.Channel Release; public Lock() { // Create j and init channels (elided) j.When(Acquire).And(Release).Do(() => { }); Release(); // initially free } } Producers/Consumers using Microsoft.Research.Joins; class Buffer { public readonly Asynchronous.Channel Put; public readonly Synchronous .Channel Get; public Buffer() { Join j = Join.Create(); // allocate a Join object j.Init(out Put); // bind its channels j.Init(out Get); j.When(Get).And(Put).Do // register chord (t => { return t; }); } } Reader-writer locking using Microsoft.Research.Joins; class ReaderWriterLock { private readonly Asynchronous.Channel idle; private readonly Asynchronous.Channel shared; public readonly Synchronous.Channel AcqR, AcqW, RelR, RelW; public ReaderWriterLock() { // Create j and init channels (elided) j.When(AcqR).And(idle).Do(() => shared(1)); j.When(AcqR).And(shared).Do(n => shared(n + 1)); j.When(RelR).And(shared).Do(n => { if (n == 1) { idle(); } else { shared(n - 1); } }); j.When(AcqW).And(idle).Do(() => { }); j.When(RelW).Do(() => idle()); idle(); // initially free } } Semaphores using Microsoft.Research.Joins; class Semaphore { public readonly Synchronous.Channel Acquire; public readonly Asynchronous.Channel Release; public Semaphore(int n) { // Create j and init channels (elided) j.When(Acquire).And(Release).Do(() => { }); while (n > 0) { Release(); // initially n free --n; } } } let A(n) | B() = P(n) and A(n) | C() = Q(n) It represents the consumption of message arrive at a completed join model. Each state is a possibly step for the code execution and each transitions is the reception of a message to change between two steps. And so when all messages are grab, the compiler execute the body join code corresponding to the completed model joint. So in the join-calculus, the basic values are the names like on the example is A,B or C. So the two compiler representing this values with two ways. Join compiler use a vector with Two slots, the first to the name it-self and the second to a queue of pending messages. Jocaml use name like a pointer on definitions. This definitions store the others pointer of the others names with a status field and a matching date structure by message. The fundamental difference is when the guard process is executed, for the first, it was verify if all names are the pending messages ready whereas the second use only one variable and access at the others to know if the model is completed. Recent research describe the compilation scheme as the combination of two basic steps: dispatching and forwarding. The design and correctness of the dispatcher essentially stems from pattern matching theory, while inserting an internal forwarding step in communications is a natural idea, which intuitively does not change process behavior. They made the observation that the worth observing is a direct implementation of extended join-pattern matching at the runtime level would significantly complicate the management of message queues, which would then need to be scanned in search of matching messages before consuming them. class JoinExample { int fragment1() & fragment2(int x) { // Will return value of x to caller of fragment1 return x; } } Asynchronous methods are defined by using the signal return type. This has the same characteristics as the void type except that the method will return immediately. When an asynchronous method is called a new thread is created to execute the body of the method. Example: class ThreadExample { signal thread(SomeObject x) { // This code will execute in a new thread } } Ordering modifiers Join fragments can be repeated in multiple Join patterns so there can be a case when multiple Join patterns are completed when a fragment is called. Such a case could occur in the example below if B(), C() and D() then A() are called. The final A() fragment completes three of the patterns so there are three possible methods that may be called. The ordered class modifier is used here to determine which Join method will be called. The default and when using the unordered class modifier is to pick one of the methods at random. With the ordered modifier the methods are prioritised according to the order they are declared. Example: class ordered SimpleJoinPattern { void A() & B() { } void A() & C() { } void A() & D() { } signal D() & E() { } } The closest related language is the Polyphonic C#. operation() -> receive {ok, sum} and {val, X} and {val, Y} -> {sum, X + Y}; {ok, mult} and {val, X} and {val, Y} -> {mult, X * Y}; {ok, sub} and {val, X} and {val, Y} -> {sub, X - Y}; end end Guards provides additional filtering not expressing in terms of patterns. Limited number of expression without side-effects receive {Transaction, M} and {limit, Lower, Upper} when (Lower commit_transaction(M, Transaction) end With Non-linear patterns, messages can match multiple joins receive {get, X} and {set, X} -> {found, 2, X} end ... receive {Pin, id} and {auth, Pin} and {commit, Id} -> perform_transaction(Pin, Id) end propagation allows for copying correct messages instead of removing them. receive prop({session, Id}) and {act, Action, Id} -> perform_action(Action, Id); {session, Id} and {logout, Id} -> logout_user(Id) end ... receive {Pin, id} and {auth, Pin} and {commit, Id} -> perform_transaction(Pin, Id) end Synchronous calls receive {accept, Pid1} and {asynchronous, Value} and {accept, Pid2} -> Pid1 ! {ok, Value}, Pid2 ! {ok, Value} end import std; template class Buffer: public Joint { public: Async put; Synchronous get; Buffer() { chord(get, put, &Buffer::chordBody); } V chordBody(void_t g, V p) { return p; } }; This example demonstrates a thread safe buffer and message queue with the basic operations put and get. public class Buffer { public String get() & public async put(String s) { return s; } } This is a simple buffer example. public handler Get2 long () & channel c1 (long x) & channel c2 (long y) { return (x + y); } This example demonstrates the using of chords as a synchronization tool. using System; class Test13 { int Receive() & async Send(int x) { return x * x; } public static void Main(string[] args) { Test13 t = new Test13(); t.Send(2); Console.WriteLine(t.Receive()); } } This example demonstrates how to use joins. type coins = Nickel | Dime and drinks = Coffee | Tea and buttons = BCoffee | BTea | BCancel;; (* def defines a Join-pattern set clause * "&" in the left side of = means join (channel synchronism) * "&" in the right hand side means: parallel process * synchronous_reply :== "reply" [x] "to" channel_name * synchronous channels have function-like types (`a -> `b) * asynchronous channels have types (`a Join.chan) * only the last statement in a pattern rhs expression can be an asynchronous message * 0 in an asynchronous message position means STOP ("no sent message" in CSP terminology). *) def put(s) = print_endline s ; 0 (* STOP *) ;; (* put: string Join.chan *) def serve(drink) = match drink with Coffee -> put("Cofee") | Tea -> put("Tea") ;; (* serve: drinks Join.chan *) def refund(v) = let s = Printf.sprintf "Refund %d" v in put(s) ;; (* refund: int Join.chan *) let new_vending serve refund = let vend (cost:int) (credit:int) = if credit >= cost then (true, credit - cost) else (false, credit) in def coin(Nickel) & value(v) = value(v+5) & reply () to coin or coin(Dime) & value(v) = value(v+10) & reply () to coin or button(BCoffee) & value(v) = let should_serve, remainder = vend 10 v in (if should_serve then serve(Coffee) else 0 (* STOP *)) & value(remainder) & reply () to button or button(BTea) & value(v) = let should_serve, remainder = vend 5 v in (if should_serve then serve(Tea) else 0 (* STOP *)) & value(remainder) & reply () to button or button(BCancel) & value(v) = refund( v) & value(0) & reply () to button in spawn value(0) ; coin, button (* coin, button: int -> unit *) ;; (* new_vending: drink Join.chan -> int Join.chan -> (int->unit)*(int->unit) *) let ccoin, cbutton = new_vending serve refund in ccoin(Nickel); ccoin(Nickel); ccoin(Dime); Unix.sleep(1); cbutton(BCoffee); Unix.sleep(1); cbutton(BTea); Unix.sleep(1); cbutton(BCancel); Unix.sleep(1) (* let the last message show up *) ;; gives Coffee Tea Refund 5 data Coins = Nickel | Dime; data Drinks = Coffee | Tea; data Buttons = BCoffee | BTea | BCancel; type Int = int 32 ; type String = string ; show u = u as string ; box coffee in ( coin :: Coins, button :: Buttons, value :: Int ) -- input channels out ( drink_outp :: String, value’ :: Int, refund_outp :: String) -- named outputs match -- * wildcards for unfilled outputs, and unconsumed inputs ( Nickel, *, v) -> ( *, v + 5, *) | ( Dime, *, v) -> ( *, v + 10, *) | ( *, BCoffee, v) -> vend Coffee 10 v | ( *, BTea, v) -> vend Tea 5 v | ( *, BCancel, v) -> let refund u = "Refund " ++ show u ++ "\n" in ( *, 0, refund v) vend drink cost credit = if credit >= cost then ( serve drink, credit - cost, *) else ( *, credit, *); serve drink = case drink of Coffee -> "Cofee\n" Tea -> "Tea\n" box control in (c :: char) out (coin :: Coins, button:: Buttons) match 'n' -> (Nickel, *) | 'd' -> (Dime, *) | 'c' -> (*, BCoffee) | 't' -> (*, BTea) | 'x' -> (*, BCancel) | _ -> (*, *) stream console_outp to "std_out" ; stream console_inp from "std_in" ; -- dataflow wiring wire cofee -- inputs (channel origins) (control.coin, control.button, coffee.value’ initially 0) -- outputs destinations (console_outp, coffee.value, console_outp) wire control (console_inp) (coffee.coin, coffee.button) Module Buffer Public Asynchronous Put(ByVal s As String) Public Synchronous Take() As String Private Function CaseTakeAndPut(ByVal s As String) As String _ When Take, Put Return s End Function End Module This example shows all new keywords used by Concurrent Basic: Asynchronous, Synchronous and When. using Microsoft.Research.Joins; class Buffer { public readonly Asynchronous.Channel Put; public readonly Synchronous .Channel Get; public Buffer() { Join join = Join.Create(); join.Initialize(out Put); join.Initialize(out Get); join.When(Get).And(Put).Do(delegate(string s) { return s; }); } } This example shows how to use methods of the Join object. class ReaderWriterLock extends Joins { private val Sharing = new AsyncEvent[Int] val Exclusive, ReleaseExclusive = new NullarySyncEvent val Shared, ReleaseShared = new NullarySyncEvent join { case Exclusive() & Sharing(0) => Exclusive reply case ReleaseExclusive() => { Sharing(0); ReleaseExclusive reply } case Shared() & Sharing(n) => { Sharing(n+1); Shared reply } case ReleaseShared() & Sharing(1) => { Sharing(0); ReleaseShared reply } case ReleaseShared() & Sharing(n) => { Sharing(n-1); ReleaseShared reply } } Sharing(0) } With a class we declare events in regular fields. So, it's possible to use the Join construct to enable a pattern matching via a list of case declarations. That list is representing by => with on each side a part of the declaration. The left-side is a model of join pattern to show the combination of events asynchronous and synchronous and the right-side is the body of join which is executed with the join model is completed. In Scala, it's also possible to use the Scala's actor library with the join pattern. For example, an unbounded buffer: val Put = new Join1[Int] val Get = new Join class Buffer extends JoinActor { def act() { receive { case Get() & Put(x) => Get reply x } } } Scala Join and Chymyst are newer implementations of the Join Pattern, improving upon Dr. Philipp Haller's Scala Joins.

source: e01 Encyclopedia · licence: CC BY-SA 4.0 · page · source revision

Cite this

"join-pattern". 1772597600. e01 Encyclopedia. CC BY-SA 4.0. https://en.wikipedia.org/w/index.php?oldid=1341632688

JSON record · API collection · citation policy