goroutine

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
54
55
56
57
58
59
60
61
62
63
64
package main

import (
	"fmt"
	"sync"
	"time"
)

func hello(name string) {
	fmt.Println("Hello,", name)
}

type Student struct {
	RemainCourses []string
	mu            sync.Mutex
}

func (s *Student) DoHomework() {
	if len(s.RemainCourses) == 0 {
		fmt.Println("do nothing...")
		return
	}	
    
	s.mu.Lock()
    h := s.RemainCourses[0]
	if len(s.RemainCourses) == 1 {
		s.RemainCourses = nil
	} else {
		s.RemainCourses = s.RemainCourses[1:]
	}
	s.mu.Unlock()

	fmt.Println("do ", h, "")
}

func main() {

	go func() {
		fmt.Println("In 1 goroutine.")
	}()

	go func() {
		fmt.Println("In 4 goroutine.")
	}()

	go func() {
		fmt.Println("In 3 goroutine.")
	}()

	go func() {
		fmt.Println("In 2 goroutine.")
	}()

	time.Sleep(time.Second)

	s1 := Student{RemainCourses: []string{"Math", "Chinese", "English"}}
	go s1.DoHomework()
	go s1.DoHomework()
	go s1.DoHomework()
	go s1.DoHomework()
	go s1.DoHomework()

	time.Sleep(time.Second)
}
最后修改 October 10, 2024: 更新 (a4b8f85)