summary refs log tree commit diff stats
path: root/tests/threads/threadex.nim
blob: 545d1f0cc575cd3fdd6c5ec0f03b22050092684c (plain) (blame)
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
discard """
  outputsub: "All rights reserved."
"""

type
  TMsgKind = enum
    mLine, mEof
  TMsg = object {.pure, final.}
    case k: TMsgKind
    of mEof: nil
    of mLine: data: string

var
  producer, consumer: TThread[void]
  chan: TChannel[TMsg]
  printedLines = 0

proc consume() {.thread.} =
  while true:
    var x = recv(chan)
    if x.k == mEof: break
    echo x.data
    atomicInc(printedLines)

proc produce() {.thread.} =
  var m: TMsg
  var input = open("readme.txt")
  var line = ""
  while input.readLine(line):
    m.data = line
    chan.send(m)
  close(input)
  m.k = mEof
  chan.send(m)

open(chan)
createThread[void](consumer, consume)
createThread[void](producer, produce)
joinThread(consumer)
joinThread(producer)

close(chan)
echo printedLines