go實(shí)現(xiàn)多個(gè)goroutine串行執(zhí)行

實(shí)現(xiàn)方式:用map[int]func(uin32)來實(shí)現(xiàn),將要執(zhí)行的函數(shù)放入map中,用map的key來作為實(shí)現(xiàn)順序,由于map取值是無序的,所以需要對(duì)用原子操作對(duì)goroutine加上自旋鎖,使其在沒有到達(dá)它的執(zhí)行順序時(shí)進(jìn)行等待。

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是無序取值,所有更能體現(xiàn)goroutine是順序執(zhí)行的
    for index,fn := range m{
        go fn(uint32(index))
    }
    time.Sleep(10*time.Second)
}

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

//創(chuàng)建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
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容