GO语言线程管理控制方法

多的不说,上代码

package thread

import "errors"

type TPoolImpl interface {
    Del(name string) int // 删除当前名称线程 返回删除数
    Add(name string,call func(status *bool)) error // 添加线程
    Start(name string) (int, error) // 启动线程
    Stop(name string) (int, error) // 停止线程
    StartSize() int // 启动的线程数
    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
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容