summary refs log tree commit diff stats
path: root/tests/stdlib/tchannels_simple.nim
blob: dc4857c3e853d5f3df5fe075b99a7b1078b96bc4 (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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
discard """
  matrix: "--threads:on --gc:orc; --threads:on --gc:arc"
  disabled: "freebsd"
"""

import std/channels
import std/os

var chan = newChannel[string]()

# This proc will be run in another thread using the threads module.
proc firstWorker() =
  chan.send("Hello World!")

# This is another proc to run in a background thread. This proc takes a while
# to send the message since it sleeps for 2 seconds (or 2000 milliseconds).
proc secondWorker() =
  sleep(2000)
  chan.send("Another message")


# Launch the worker.
var worker1: Thread[void]
createThread(worker1, firstWorker)

# Block until the message arrives, then print it out.
var dest = ""
chan.recv(dest)
doAssert dest == "Hello World!"

# Wait for the thread to exit before moving on to the next example.
worker1.joinThread()

# Launch the other worker.
var worker2: Thread[void]
createThread(worker2, secondWorker)
# This time, use a non-blocking approach with tryRecv.
# Since the main thread is not blocked, it could be used to perform other
# useful work while it waits for data to arrive on the channel.

var messages: seq[string]
var msg = ""
while true:
  let tried = chan.tryRecv(msg)
  if tried:
    messages.add move(msg)
    break
  
  messages.add "Pretend I'm doing useful work..."
  # For this example, sleep in order not to flood stdout with the above
  # message.
  sleep(400)

# Wait for the second thread to exit before cleaning up the channel.
worker2.joinThread()

# Clean up the channel.
doAssert chan.close()
doAssert messages[^1] == "Another message"
doAssert messages.len >= 2


block:
  let chan0 = newChannel[int]()
  let chan1 = chan0
  block:
    let chan3 = chan0
    let chan4 = chan0
e953e'>^
bc643692 ^
047296d8 ^
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





                                                                          
                             

                                                                                   






                                                            

                                                                                                                 

                             
 
                                                     
 





                                                                                                            




                                                                           

                                                         

                                                                                                            

 
                                                                                           
                                                                                    
                         

                

                                                                                                                       
                

 
                                             
                                                          
                                              
                                                                         
                                                                                                                                                 
                                                          
     


           


                                         
                        
 
//: So far you can have global variables by not setting default-space, and
//: local variables by setting default-space. You can isolate variables
//: between those extremes by creating 'surrounding' spaces.
//:
//: (Surrounding spaces are like lexical scopes in other languages.)

:(scenario surrounding_space)
# location 1 in space 1 refers to the space surrounding the default space, here 20.
recipe main [
  # pretend shared:array:location; in practice we'll use new
  10:number <- copy 0  # refcount
  11:number <- copy 5  # length
  # pretend shared:array:location; in practice we'll use new
  20:number <- copy 0  # refcount
  21:number <- copy 5  # length
  # actual start of this recipe
  default-space:address:shared:array:location <- copy 10/unsafe
  0:address:shared:array:location/names:dummy <- copy 20/unsafe  # later layers will explain the /names: property
  1:number <- copy 32
  1:number/space:1 <- copy 33
]
recipe dummy [  # just for the /names: property above
]
# chain space: 10 + /*skip refcount*/1 + /*skip length*/1
+mem: storing 20 in location 12
# store to default space: 10 + /*skip refcount*/1 + /*skip length*/1 + /*index*/1
+mem: storing 32 in location 13
# store to chained space: /*contents of location 12*/20 + /*skip refcount*/1 + /*skip length*/1 + /*index*/1
+mem: storing 33 in location 23

//: If you think of a space as a collection of variables with a common
//: lifetime, surrounding allows managing shorter lifetimes inside a longer
//: one.

:(replace{} "long long int space_base(const reagent& x)")
long long int space_base(const reagent& x) {
  long long int base = current_call().default_space ? (current_call().default_space+/*skip refcount*/1) : 0;
  return space_base(x, space_index(x), base);
}

long long int space_base(const reagent& x, long long int space_index, long long int base) {
//?   trace(9999, "space") << "space-base: " << space_index << " " << base << end();
  if (space_index == 0) {
    return base;
  }
  long long int result = space_base(x, space_index-1, get_or_insert(Memory, base+/*skip length*/1))+/*skip refcount*/1;
//?   trace(9999, "space") << "space-base: " << space_index << " " << base << " => " << result << end();
  return result;
}

long long int space_index(const reagent& x) {
  for (long long int i = 0; i < SIZE(x.properties); ++i) {
    if (x.properties.at(i).first == "space") {
      if (!x.properties.at(i).second || x.properties.at(i).second->right)
        raise_error << maybe(current_recipe_name()) << "/space metadata should take exactly one value in " << x.original_string << '\n' << end();
      return to_integer(x.properties.at(i).second->value);
    }
  }
  return 0;
}

:(scenario permit_space_as_variable_name)
recipe main [
  space:number <- copy 0
]