Post

Go concurrency

Introduction to Go concurrency using goroutines, including basic goroutine invocation and passing arguments to anonymous goroutine functions.

This example shows two ways to use goroutines in Go. The first launches a named function as a goroutine with the go keyword. The second demonstrates an anonymous goroutine function that receives a copy of the variable as an argument, avoiding a common race condition where the goroutine would otherwise reference a variable that has been modified in the main goroutine.

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
// package main

// import (
// 	"fmt"
// 	// "strconv"
// 	// "math"
// 	// "reflect"
// 	// "net/http"
// 	// "log"

// )

// // define interface
// type Writer interface {
// 	Write([]byte) (int, error)
// }

// type ConsoleWriter struct {}

// func (cw ConsoleWriter) Write(data []byte) (int, error) {
// 	n, err := fmt.Printf("Converts bytes to string: %v\n", string(data))
// 	return n, err
// }

// func main()  {
// 	var w Writer = ConsoleWriter{}
// 	w.Write([]byte("101010100001"))
// }

package main

import (
	"fmt"
	"time"
)

func sayHello()  {
	fmt.Printf("Say hello\n")
}

func main()  {
	go sayHello()
	time.Sleep(100 * time.Millisecond)

// bad approach
var msg string = "hello"
go func (i string)  {
	fmt.Printf("%v\n", i)
}(msg)
msg = "Goodbye"
time.Sleep(100 * time.Millisecond)
}

This post is licensed under CC BY 4.0 by the author.