golang协程如何关闭


当前第2页 返回上一页

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

type Service struct {

        // Other things

  

        ch        chan bool

        waitGroup *sync.WaitGroup

}

  

func NewService() *Service {

    s := &Service{

                // Init Other things

                ch:        make(chan bool),

                waitGroup: &sync.WaitGroup{},

    }

  

    return s

}

  

func (s *Service) Stop() {

        close(s.ch)

        s.waitGroup.Wait()

}

  

func (s *Service) Serve() {

        s.waitGroup.Add(1)

        defer s.waitGroup.Done()

  

        for {

                select {

                case <-s.ch:

                        fmt.Println("stopping...")

                        return

                default:

                }

                s.waitGroup.Add(1)

                go s.anotherServer()

    }

}

func (s *Service) anotherServer() {

        defer s.waitGroup.Done()

        for {

                select {

                case <-s.ch:

                        fmt.Println("stopping...")

                        return

                default:

                }

  

                // Do something

        }

}

  

func main() {

  

        service := NewService()

        go service.Serve()

  

        // Handle SIGINT and SIGTERM.

        ch := make(chan os.Signal)

        signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

        fmt.Println(<-ch)

  

        // Stop the service gracefully.

        service.Stop()

}

更多golang知识请关注golang教程栏目。

以上就是golang协程如何关闭的详细内容,更多文章请关注木庄网络博客!!

返回前面的内容

相关阅读 >>

go语言之并发

我为何从php 加入到 go 的潮流!

毛剑:bilibili 的 go 服务实践(上篇)

[译]go语言内存布局

golang判断字符是否存在字符串中

go-const

go - httpclient 常用操作

golang 有gc吗

golang读锁有什么用

golang 面向对象编程

更多相关阅读请进入《golang》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...