go实现多个goroutine串行执行

实现方式:用map[int]func(uin32)来实现,将要执行的函数放入map中,用map的key来作为实现顺序,由于map取值是无序的,所以需要对用原子操作对goroutine加上自旋锁,使其在没有到达它的执行顺序时进行等待。

package main

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

type operation func(string)
func main(){
    var count uint32 = 1
    m := generate(&count,5,withPrint())
    //var i = uint32(0)、

      //由于map是无序取值,所有更能体现goroutine是顺序执行的
    for index,fn := range m{
        go fn(uint32(index))
    }
    time.Sleep(10*time.Second)
}

func withPrint()operation{
    return func(s string) {
        println(s)
    }
}

//创建map
func generate(cptr *uint32,total int,op operation)map[int]func(uint32){
    var m = make(map[int]func(order uint32),total)
    for i:=1;i<=total;i++ {
        m[i] = func(order uint32) {
            for  {
                              //比较order和count的值是否相等,不想等就自旋
                if !atomic.CompareAndSwapUint32(cptr,order,order){
                    time.Sleep(500*time.Millisecond)
                }else {
                    break
                }
            }
            s := fmt.Sprintf("this is goroutine %d",order)
            op(s)
            atomic.AddUint32(cptr,1)
        }
    }
    return m
}

你可能感兴趣的:(go实现多个goroutine串行执行)