Skip to content

Instantly share code, notes, and snippets.

lpfib :: Int -> (Int, [Int])
lpfib 0 = (1, [1])
lpfib 1 = (1, [1, 1])
lpfib n = aq `par` bq `pseq` (a + b, as ++ bs ++ [a + b])
where aq@(a, as) = lpfib (n - 1)
bq@(b, bs) = lpfib (n - 2)
-- por ejemplo
main = getArgs >>= mapM_ print . snd . lpfib . read . head
Anton, I'm not sure what is the *exact* problem you has solved.
"Deterministic logging in presence of parallelism is not hard"
Your approach, for N parallel process, use (N - 1) * sizeEachLog amount of memory (if not first sizeEachLog is consumed on start then N * sizeEachLog).
The sequential version use no memory.
I think is not the same thing.
static int fibonacci(SyncLink s, int n, Action<int> action) {
Thread.Sleep(1000); // para ver cómo procesos rápidos esperan a otros lentos
if(n < 2)
return s.End(() => action(n), () => 1);
else
return s.Fork(() => action(n)
, ss => fibonacci(ss, n - 1, action)
var r =
SyncLink.Run(
s => fibonacci(s, 4, n => Console.WriteLine(n)),
false);
Console.WriteLine("Fibonacci: {0}", r);
/*
4
static IEnumerable<int> enumerableFib(int N) {
var q = new BlockingCollection<int>();
new Thread(() => {
SyncLink.Run(s => fibonacci(s, N, n => q.Add(n)));
// recuerda que por defecto Run espera a terminar
q.CompleteAdding();
}).Start();
return q.GetConsumingEnumerable();
}
foreach(var n in enumerableFib(4))
Console.WriteLine("e ~> {0}", n);
/*
e ~> 4
e ~> 3
e ~> 2
e ~> 1
e ~> 0
static IEnumerable<Tuple<string, string>> enumDirectoryHashes(string root) {
var q = new BlockingCollection<Tuple<string, string>>();
Func<SyncLink, IEnumerable<string>, bool> branchs = null;
Func<SyncLink, string, bool> node = (s, path) => {
if(File.Exists(path)) {
var hash = GetMD5HashFromFile(path); // éste se hace también en paralelo
s.End(() => q.Add(Tuple.Create(path, hash)), // sólo la escritura del resultado es sincrónica
foreach(var hashedFile in enumDirectoryHashes(@"d:\tmp\SignalR"))
Console.WriteLine("{0}: {1}", hashedFile.Item2, hashedFile.Item1);
/*
62e6064204c49910fd8b71dca206a4a5: d:\tmp\SignalR\.gitattributes
99914b932bd37a50b983c5e7c90ae93b: d:\tmp\SignalR\build\_Chutzpah.coverage.json
6985c7123edda3e70cc160947e02681c: d:\tmp\SignalR\build\applicationHost.config
07667ca80fc1044c16e711d3ebd18f41: d:\tmp\SignalR\build\Build.tasks
4268e58481e987e5287e6127911a8a6d: d:\tmp\SignalR\build\Microsoft.AspNet.SignalR.OpenCover.targets
907c17a99bf4ddc55e90b5abcffccea7: d:\tmp\SignalR\build\Microsoft.AspNet.SignalR.Projects.Properties.proj
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Security.Cryptography;