Loading search index…
No recent searches
No results for "Query here"
A goroutine is a lightweight thread of execution.
void f(string from) { for (int i = 0; i < 3; i++) { Print(from + " : " + i); } } void main() { // Calling the function f in the usual way, running it synchronously. f("direct"); // To invoke this function in another thread, we use the Thread function. // This new thread will execute concurrently with the main thread. Thread t1 = Thread::Create(@f, "goroutine"); // You can also start a new thread for an anonymous function call. Thread t2 = Thread::Create(function() { Print("going"); }); // Wait for the threads to finish. t1.join(); t2.join(); Print("done"); }
When we run this program, we see the output of the main call first, then the output of the two threads. The thread’s output may be interleaved because the threads are being run concurrently by the runtime.
$ as run goroutines.as direct : 0 direct : 1 direct : 2 goroutine : 0 going goroutine : 1 goroutine : 2 done