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 - options模式(函数式选项模式)

golang中将字节流转为protobuf

go中控制并发的两种方式

吊打jd_seckill,go语言版免配置抢茅台程序,实力接盘~

如何用go开发一个区块链项目:abtc

golang 如何类型转换

手撸golang 仿spring ioc/aop 之8 扫码3

go开源说第四期:go-zero解读与最佳实践(上)

gorm 如果使用同一个sql.db 去开协程。为什么速度会比单线程跑快很多

一周 go world 新鲜事

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




打赏

取消

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

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

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

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

评论

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