GO語言線程管理控制方法

多的不說,上代碼

package thread

import "errors"

type TPoolImpl interface {
    Del(name string) int // 刪除當(dāng)前名稱線程 返回刪除數(shù)
    Add(name string,call func(status *bool)) error // 添加線程
    Start(name string) (int, error) // 啟動線程
    Stop(name string) (int, error) // 停止線程
    StartSize() int // 啟動的線程數(shù)
    Names() []string // 獲取線程中所有線程名稱
}

type TPool struct {
    thread []*thread
}

type thread struct {
    name string
    status bool
    call func(status *bool)
}

func (the *TPool) Del(name string) int {
    result := 0
    for dex := range the.thread {
        if the.thread[dex].name == name {
            the.thread[dex].status = false
            the.thread = append(the.thread[:dex], the.thread[dex + 1:]...)
            result ++
            break
        }
    }
    return result
}

func (the *TPool) Add(name string,call func(status *bool)) error {
    for dex := range the.thread {
        if the.thread[dex].name == name {
            return errors.New("this name thread is not empty")
        }
    }
    the.thread = append(the.thread, &thread{name: name, call: call, status: false})
    return nil
}

func (the *TPool) Start(name string) (int, error) {
    has := 0
    for dex := range the.thread {
        if !the.thread[dex].status && the.thread[dex].name == name {
            has ++
            the.thread[dex].status = true
            go the.thread[dex].call(&the.thread[dex].status)
        }
    }
    if 0 == has {
        return has, errors.New("not fund stop thread")
    }
    return has, nil
}

func (the *TPool) Stop(name string) (int, error) {
    has := 0
    for dex := range the.thread {
        if the.thread[dex].status && the.thread[dex].name == name {
            has ++
            the.thread[dex].status = false
        }
    }
    if 0 == has {
        return has, errors.New("not fund start thread")
    }
    return has, nil
}

func (the *TPool) StartSize() int {
    count := 0
    for dex := range the.thread {
        if the.thread[dex].status {
            count ++
        }
    }
    return count
}

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

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

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