0
0

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 1 year has passed since last update.

Goroutineとselectとchannelを使って共同作業

Posted at

田中君:1作業あたり1秒
鈴木君:1作業あたり1秒

ルール

  • 作業6個分になったら仕事終了
  • 仕事が終了するまでにかかった時間を計測する

田中君だけで作業をした場合 (鈴木君のgoroutineをコメントアウト)


package main

import (
	"fmt"
	"time"
)

var total_work = []string{}

func tanaka(ch chan string) {
	for {
		time.Sleep(1 * time.Second)
		ch <- "作業"
	}
}

func suzuki(ch chan string) {
	for {
		time.Sleep(1 * time.Second)
		ch <- "作業"
	}
}

func main() {
	start_time := time.Now()
	c1 := make(chan string)
	c2 := make(chan string)
	go tanaka(c1)
	// go suzuki(c2)

	for {
		fmt.Println(total_work)
		if len(total_work) >= 6 {
			elapsed_time := time.Since(start_time)
			fmt.Printf("経過時間 : %v\n", elapsed_time)
			break
		}
		select {
		case unit_work1 := <-c1:
			total_work = append(total_work, unit_work1)
			fmt.Println(unit_work1)
		case unit_work2 := <-c2:
			fmt.Println(unit_work2)
			total_work = append(total_work, unit_work2)
		}
	}
}


実行結果


[]
作業
[作業]
作業
[作業 作業]
作業
[作業 作業 作業]
作業
[作業 作業 作業 作業]
作業
[作業 作業 作業 作業 作業]
作業
[作業 作業 作業 作業 作業 作業]
経過時間 : 6.0380414s

田中君と鈴木君が共同作業した場合


package main

import (
	"fmt"
	"time"
)

var total_work = []string{}

func tanaka(ch chan string) {
	for {
		time.Sleep(1 * time.Second)
		ch <- "作業"
	}
}

func suzuki(ch chan string) {
	for {
		time.Sleep(1 * time.Second)
		ch <- "作業"
	}
}

func main() {
	start_time := time.Now()
	c1 := make(chan string)
	c2 := make(chan string)
	go tanaka(c1)
	go suzuki(c2)

	for {
		fmt.Println(total_work)
		if len(total_work) >= 6 {
			elapsed_time := time.Since(start_time)
			fmt.Printf("経過時間 : %v\n", elapsed_time)
			break
		}
		select {
		case unit_work1 := <-c1:
			total_work = append(total_work, unit_work1)
			fmt.Println(unit_work1)
		case unit_work2 := <-c2:
			fmt.Println(unit_work2)
			total_work = append(total_work, unit_work2)
		}
	}
}

実行結果


[]
作業
[作業]     
作業       
[作業 作業]
作業
[作業 作業 作業]     
作業
[作業 作業 作業 作業]
作業
[作業 作業 作業 作業 作業]
作業
[作業 作業 作業 作業 作業 作業]
経過時間 : 3.0256638s

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?