前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >go笔记:go语言中使用协程异步并行

go笔记:go语言中使用协程异步并行

作者头像
超级大猪
发布2019-11-22 09:37:23
9430
发布2019-11-22 09:37:23
举报
文章被收录于专栏:大猪的笔记大猪的笔记

在go中,有了协程和chan,就能轻松而优雅的实现很多模式。

而引入future的思想可以解放思维。

代码语言:javascript
复制
package utils

import (
    "sync"
    "time"
)

/*
Future 是一个未来的任务的抽象。和python里的那个有点类似。
在异步任务中SetResult,在GetResult的时候会等待result生成,或者超时。
使用姿势:
tasks := make([]*utils.Future, 0)
for i := 0; i < 10; i++ {
    future := utils.NewFuture()
    tasks = append(tasks, future)
    go func(result int) {
        time.Sleep(time.Second * time.Duration(rand.Int63n(10)))
        future.SetResult(result)
    }(i)
}

for _, item := range tasks {
    ret, ok := item.GetResult().(int)
    if ok {
        fmt.Println(ret)
    } else {
        fmt.Println("failed")
    }
}
*/

type Future struct {
    isfinished bool
    result     interface{}
    resultchan chan interface{}
    l          sync.Mutex
}

func (f *Future) GetResult() interface{} {
    f.l.Lock()
    defer f.l.Unlock()
    if f.isfinished {
        return f.result
    }

    select {
    // timeout
    case <-time.Tick(time.Second * 6):
        f.isfinished = true
        f.result = nil
        return nil
    case f.result = <-f.resultchan:
        f.isfinished = true
        return f.result
    }
}

func (f *Future) SetResult(result interface{}) {
    if f.isfinished == true {
        return
    }
    f.resultchan <- result
    close(f.resultchan)
}

func NewFuture() *Future {
    return &Future{
        isfinished: false,
        result:     nil,
        resultchan: make(chan interface{}, 1),
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-08-26 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档