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 语言数据类型

golang为什么那么火?

一周 go world 新鲜事

关于golang的那些事(八)-- 使用共享变量实现并发

golang map 不排序怎么办

golang中线程和协程的区别是什么

lal-开源go语言音视频流媒体服务器

golang适合web开发吗?

【gocn酷go推荐】goroutine 泄漏防治神器 goleak

golang导出csv乱码解决方法

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




打赏

取消

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

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

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

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

评论

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