1. 程式人生 > >Golang多個goroutine順序輸出自然數序列

Golang多個goroutine順序輸出自然數序列

package main

import (
	"sync/atomic"
	"time"
	"fmt"
)

func main() {
	var number uint32 = 10
	//count相當於一個接力棒
	var count uint32
	trigger := func(i uint32, fn func()) {
		//自旋鎖
		for {
			if n := atomic.LoadUint32(&count); n == i {
				fn()
				//一定要在執行完函式後才原子加1
				atomic.AddUint32(&count, 1)
				break
			}
			time.Sleep( 1 * time.Millisecond)
		}
	}

	for i := uint32(0); i < number; i++ {
		go func(i uint32) {
			fn := func() {
				fmt.Println(i)
			}
			trigger(i, fn)
		}(i)
	}
	trigger(number, func(){})
	//會按照自然數順序列印(一定是這樣)
}