@@ -5,6 +5,7 @@ discard """
55
66import threading/ channels
77import std/ [os, logging, unittest]
8+ from tchannels_simple import runMultithreadTest
89
910suite " testing Chan with overwrite mode" :
1011 var logger = newConsoleLogger (levelThreshold= lvlInfo)
@@ -40,52 +41,7 @@ suite "testing Chan with overwrite mode":
4041
4142 var chan = newChan [string ](elements = 4 , overwrite = true )
4243
43- # Launch the worker.
44- var worker1: Thread [void ]
45- var worker2: Thread [void ]
44+ runMultithreadTest (chan)
4645
47- # # start worker1
48- createThread (worker1, proc () =
49- chan.send (" Hello World!" ))
50-
51- # Block until the message arrives, then print it out.
52- block :
53- var dest = " "
54- chan.recv (dest)
55- doAssert dest == " Hello World!"
56-
57- # Wait for the thread to exit before moving on to the next example.
58- worker1.joinThread ()
59-
60- # Launch the other worker.
61- createThread (worker2, proc () =
62- # This is another proc to run in a background thread. This proc takes a while
63- # to send the message since it sleeps for 2 seconds (or 2000 milliseconds).
64- sleep (2000 )
65- chan.send (" Another message" ))
66-
67- # This time, use a non-blocking approach with tryRecv.
68- # Since the main thread is not blocked, it could be used to perform other
69- # useful work while it waits for data to arrive on the channel.
70- var messages: seq [string ]
71- block :
72- var msg = " "
73- while true :
74- let tried = chan.tryRecv (msg)
75- if tried:
76- messages.add move (msg)
77- break
78-
79- messages.add " Pretend I'm doing useful work..."
80- # For this example, sleep in order not to flood stdout with the above
81- # message.
82- sleep (400 )
83-
84- # Wait for the second thread to exit before cleaning up the channel.
85- worker2.joinThread ()
86-
87- # Clean up the channel.
88- doAssert messages[^ 1 ] == " Another message"
89- doAssert messages.len >= 2
9046
9147
0 commit comments