5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

golang の channel のブロックがよくわからん

Last updated at Posted at 2015-11-11

golang の channel のブロックがよくわからん

っていう人(2日前の自分とか)は、これビルドして実行して Ctrl+C 連打してみるといいと思う。

SIGINT 拾っちゃってるので、停めるときは SIGTERM 送るとよい。

main.go
package main

import (
	"fmt"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"time"
)

func main() {

	var wg sync.WaitGroup
	ch := make(chan int, 10)

	wg.Add(1)
	go func(c chan int) {
		for {
			i := <-c
			fmt.Println(fmt.Sprintf("rcv: %d", i))
			time.Sleep(500 * time.Millisecond)
		}
	}(ch)

	signal_chan := make(chan os.Signal, 16)
	signal.Notify(signal_chan,
		syscall.SIGINT,
	)
	go func() {
		cnt := 0
		for {
			sig := <-signal_chan
			switch sig {
			case syscall.SIGINT:
				cnt++
				fmt.Println(fmt.Sprintf("send: %d", cnt))
				ch <- cnt
			}
		}
	}()

	wg.Wait()
}
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?