threadex.nim 896 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. discard """
  2. disabled: i386
  3. outputsub: "Just a simple text for test"
  4. """
  5. type
  6. TMsgKind = enum
  7. mLine, mEof
  8. TMsg = object
  9. case k: TMsgKind
  10. of mEof: discard
  11. of mLine: data: string
  12. var
  13. producer, consumer: Thread[void]
  14. chan: Channel[TMsg]
  15. printedLines = 0
  16. prodId: int
  17. consId: int
  18. proc consume() {.thread.} =
  19. consId = getThreadId()
  20. while true:
  21. var x = recv(chan)
  22. if x.k == mEof: break
  23. echo x.data
  24. atomicInc(printedLines)
  25. proc produce() {.thread.} =
  26. prodId = getThreadId()
  27. var m: TMsg
  28. var input = open("tests/dummy.txt")
  29. var line = ""
  30. while input.readLine(line):
  31. m.data = line
  32. chan.send(m)
  33. close(input)
  34. m = TMsg(k: mEof)
  35. chan.send(m)
  36. open(chan)
  37. createThread[void](consumer, consume)
  38. createThread[void](producer, produce)
  39. joinThread(consumer)
  40. joinThread(producer)
  41. close(chan)
  42. doAssert prodId != consId
  43. echo printedLines