v / examples / coroutines / simple_coroutines.v
62 lines · 57 sloc · 1.27 KB · a80bc2331450fc28c900097f8afafe173f161d27
Raw
1// vtest build: false // This should be build with: v -use-coroutines simple_coroutines.v
2// Note: the Photon wrapper is not yet trivial enough to build/install on the CI.
3import coroutines
4import time
5import os
6import net.http
7
8fn foo(a int) {
9 for {
10 println('1hello from foo() a=${a}')
11 // C.printf(c'hello from foo() a=%d\n', a)
12 coroutines.sleep(1 * time.second)
13 }
14}
15
16fn foo2(a int) {
17 mut i := 0
18 for {
19 println('hello from foo2() a=${a}')
20 // C.printf(c'hello from foo2() a=%d\n', a)
21 coroutines.sleep(2 * time.second)
22 i++
23 resp := http.get('https://vlang.io/utc_now') or { panic(err) }
24 println(resp)
25 mut f := os.create('/tmp/FOO2_a${i}') or { panic(err) }
26 f.write_string(resp.body) or { panic(err) }
27 f.close()
28 }
29}
30
31fn foo3(a int) {
32 for {
33 println('hello from foo3() a=${a}')
34 // C.printf(c'hello from foo3() a=%d\n', a)
35 coroutines.sleep(3 * time.second)
36 }
37}
38
39fn foo4(a int) {
40 for {
41 println('hello from foo4() a=${a}')
42 // C.printf(c'hello from foo4() a=%d\n', a)
43 coroutines.sleep(3 * time.second)
44 }
45}
46
47fn main() {
48 go foo(10)
49 go foo2(20)
50 go foo3(30)
51 go foo3(40)
52 $if is_coroutine ? {
53 println('IS COROUTINE=true')
54 } $else {
55 println('IS COROUTINE=false')
56 }
57 for {
58 println('hello from MAIN')
59 coroutines.sleep(1 * time.second)
60 }
61 println('done')
62}
63