0votos

Cronómetro con Threads en Java en Haskell

por josejuan hace 5 años

Por ejemplo usando canales para que los relojes envíen los datos.

En este desafío deberemos crear un cronómetro con el uso de Threads.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import Control.Concurrent 
import Control.Concurrent.Chan 
import Control.Monad (forever, forM_, replicateM_) 
 
data ThreadedClock = ThreadedClock { name :: String 
                                   , stepSegs :: Int 
                                   , alarmEachNSteps :: Int 
                                   } deriving (Show, Read) 
 
 
threadedClock :: Chan String -> ThreadedClock -> IO () 
threadedClock out' (ThreadedClock title delay alarm) = forever (doStep alarm) 
    where out msg = writeChan out' $ "Clock \"" ++ title ++ "\": " ++ msg 
          doStep 0 = out "ALARM!!!!" 
          doStep n = do threadDelay (1000000 * delay) 
                        out $ "steps to alarm " ++ show n 
                        doStep (n - 1) 
 
main = do 
    config <- getContents 
    let clocks :: [ThreadedClock] 
        clocks = read config 
    out <- newChan 
    mapM_ (forkIO . threadedClock out) clocks 
    forever $ do msg <- readChan out 
                 putStrLn msg 
 
{- ==================================================================== 
 
# por ejemplo, con el archivo de relojes: 
 
$ cat clocks.config 
 
[ ThreadedClock { name = "Beber" 
                , stepSegs = 1 
                , alarmEachNSteps = 5 
, ThreadedClock { name = "Comer" 
                , stepSegs = 2 
                , alarmEachNSteps = 8 
 
# podríamos ejecutar 
 
$ cat clocks.config | runghc threadClocks.hs 
Clock "Beber": steps to alarm 5 
Clock "Comer": steps to alarm 8 
Clock "Beber": steps to alarm 4 
Clock "Beber": steps to alarm 3 
Clock "Beber": steps to alarm 2 
Clock "Comer": steps to alarm 7 
Clock "Beber": steps to alarm 1 
Clock "Beber": ALARM!!!! 
Clock "Beber": steps to alarm 5 
Clock "Comer": steps to alarm 6 
Clock "Beber": steps to alarm 4 
Clock "Beber": steps to alarm 3 
Clock "Comer": steps to alarm 5 
Clock "Beber": steps to alarm 2 
Clock "Comer": steps to alarm 4 
Clock "Beber": steps to alarm 1 
Clock "Beber": ALARM!!!! 
Clock "Beber": steps to alarm 5 
Clock "Beber": steps to alarm 4 
Clock "Comer": steps to alarm 3 
Clock "Beber": steps to alarm 3 
Clock "Beber": steps to alarm 2 
Clock "Comer": steps to alarm 2 
Clock "Beber": steps to alarm 1 
Clock "Beber": ALARM!!!! 
Clock "Beber": steps to alarm 5 
Clock "Comer": steps to alarm 1 
Clock "Comer": ALARM!!!! 
Clock "Beber": steps to alarm 4 
Clock "Comer": steps to alarm 8 
etc... 
 
-} 

Comenta la solución

Tienes que identificarte para poder publicar tu comentario.