Last active
August 29, 2015 13:56
-
-
Save josejuan/8924391 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SyncLink { | |
private Semaphore _win, _wou; | |
private SyncLink(Semaphore win, Semaphore wou) { | |
_win = win; | |
_wou = wou; | |
} | |
// ésta es la acción pospuesta del cuadrado VERDE | |
private static void delaySync(Semaphore win, Semaphore wou, Action syncAction) { | |
new Thread(() => { // Dejaremos en el aire... | |
win.WaitOne(); // ...esperando al anterior en la lista... | |
syncAction(); // ...la acción que lanzaremos... | |
wou.Release(); // ...antes de darle paso al siguiente en la lista. | |
}).Start(); | |
} | |
// inicia una ejecución paralela de un árbol con flujo sincrónico | |
public static C Run<C>(Func<SyncLink, C> root, bool wait = true) { | |
var w = new Semaphore(0, 1); | |
var r = root(new SyncLink(new Semaphore(1, 1), w)); | |
if(wait) // permite sincronizar el flujo VERDE y el AZUL (o no) | |
w.WaitOne(); | |
return r; | |
} | |
// las hojas del árbol cierran el circuito, tras efectuar su acción sincronizada | |
public C End<C>(Action syncAction, Func<C> end) { | |
delaySync(_win, _wou, syncAction); | |
return end(); | |
} | |
// la operación de división, creamos dos semáforos intermedios sincronizados | |
public C Fork<A, B, C>( Action syncAction | |
, Func<SyncLink, A> left | |
, Func<SyncLink, B> right, Func<A, B, C> join) { | |
var u = new Semaphore(0, 1); | |
var v = new Semaphore(0, 1); | |
// cuadrado verde | |
delaySync(_win, u, syncAction); | |
// cuadrado azul | |
A ra = default(A); | |
B rb = default(B); | |
var a = new Thread(() => ra = left(new SyncLink(u, v))); | |
var b = new Thread(() => rb = right(new SyncLink(v, _wou))); | |
a.Start(); | |
b.Start(); | |
a.Join(); | |
b.Join(); | |
return join(ra, rb); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment