threadex.nim 879 B

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