1## Fiber
2Fibers are user-space threads without a scheduler; a Fiber can yield and resume its execution from the place it has exited. A Fibers (or coroutine as called in other languages) are special functions that can be interrupted at any time by the user.<br><br>When a conventional function is invoked, execution begins at the start, and once a function exits, it is finished. By contrast, Fibers can exit by calling other Fibers, which may later return to the point where they were invoked in the original coroutine:
3
4```swift
5	func main() {
6		var fiber = Fiber.create({
7			System.print("fiber 1");
8			Fiber.yield()
9			System.print("fiber 2");
10		});
11
12		System.print("main 1");
13		fiber.call()
14		System.print("main 2");
15		fiber.call()
16		System.print("main 3");
17	}
18	// Output:
19	// main 1
20	// fiber 1
21	// main 2
22	// fiber 2
23	// main 3
24```
25
26A Fiber is created with `create`:
27
28```swift
29	Fiber.create( {
30		System.print("\(self) is the current fiber")
31	})
32```
33and executed till the next `yield` with `fiber.call()`
34
35```swift
36var closure = {
37    System.print("1")
38    Fiber.yield()
39
40    System.print("2")
41    Fiber.yield()
42
43    System.print("3")
44    Fiber.yield()
45
46    System.print("Done")
47}
48
49var fiber = Fiber.create(closure)
50
51fiber.call()
52// prints 1
53
54fiber.call()
55// prints 2
56
57fiber.call()
58// prints 3
59
60fiber.call()
61// prints Done
62
63System.print(fiber.isDone())
64// prints true
65```
66
67There are 2 types of yield:
681. `Fiber.yield()` it returns the controll to the function calling `call()`
692. `Fiber.yieldWaitTime(seconds)` it returns the controll to the function calling `call()` and also store the current time internally.
70
71The later enable a call check of the total time in seconds passed since last `call()`. If the time amount is not enough the call is void and the fiber is not entered.
72
73Example:
74
75To implement a function that do some stuff every second, like a timer, a way is to use `Fiber.yieldWaitTime(seconds)`
76
77```swift
78var fiber = Fiber.create({
79  var keepGoing = true
80  while (keepGoing) {
81    keepGoing = doSomeStuff()
82    Console.write("Waiting")
83    Fiber.yieldWaitTime(1.0)
84    Console.write("Elapsed time: \(self.elapsedTime())")
85  }
86})
87
88...
89// Note: this strict loop is just for reference, not a real case.
90while (!fiber.isDone()) {
91  fiber.call()
92}
93
94```
95