oklog run包使用

2023-05-16

oklog/run 包介绍

oklog/run 包非常简单,只有一个类型,两个方法,共 60 行代码。其中 Group 是一组 actor,通过调用 Add 方法将 actor 添加到 Group 中。

// Package run implements an actor-runner with deterministic teardown. It is
// somewhat similar to package errgroup, except it does not require actor
// goroutines to understand context semantics. This makes it suitable for use in
// more circumstances; for example, goroutines which are handling connections
// from net.Listeners, or scanning input from a closable io.Reader.
package run

// Group collects actors (functions) and runs them concurrently.
// When one actor (function) returns, all actors are interrupted.
// The zero value of a Group is useful.
type Group struct {
	actors []actor
}

// Add an actor (function) to the group. Each actor must be pre-emptable by an
// interrupt function. That is, if interrupt is invoked, execute should return.
// Also, it must be safe to call interrupt even after execute has returned.
//
// The first actor (function) to return interrupts all running actors.
// The error is passed to the interrupt functions, and is returned by Run.
func (g *Group) Add(execute func() error, interrupt func(error)) {
	g.actors = append(g.actors, actor{execute, interrupt})
}

// Run all actors (functions) concurrently.
// When the first actor returns, all others are interrupted.
// Run only returns when all actors have exited.
// Run returns the error returned by the first exiting actor.
func (g *Group) Run() error {
	if len(g.actors) == 0 {
		return nil
	}

	// Run each actor.
	errors := make(chan error, len(g.actors))
	for _, a := range g.actors {
		go func(a actor) {
			errors <- a.execute()
		}(a)
	}

	// Wait for the first actor to stop.
	err := <-errors

	// Signal all actors to stop.
	for _, a := range g.actors {
		a.interrupt(err)
	}

	// Wait for all actors to stop.
	for i := 1; i < cap(errors); i++ {
		<-errors
	}

	// Return the original error.
	return err
}

type actor struct {
	execute   func() error
	interrupt func(error)
}

例子

下面例子定义了三个 actor,前两个 actor 一直等待。第三个 actor 在 3s 后结束退出。引起前两个 actor 退出。

package main

import (
	"fmt"
	"github.com/oklog/run"
	"time"
)

func main() {
	g := run.Group{}
	{
		cancel := make(chan struct{})
		g.Add(
			func() error {

				select {
				case <- cancel:
					fmt.Println("Go routine 1 is closed")
					break
				}

				return nil
			},
			func(error) {
				close(cancel)
			},
		)
	}
	{
		cancel := make(chan struct{})
		g.Add(
			func() error {

				select {
				case <- cancel:
					fmt.Println("Go routine 2 is closed")
					break
				}

				return nil
			},
			func(error) {
				close(cancel)
			},
		)
	}
	{
		g.Add(
			func() error {
				for i := 0; i <= 3; i++ {
					time.Sleep(1 * time.Second)
					fmt.Println("Go routine 3 is sleeping...")
				}
				fmt.Println("Go routine 3 is closed")
				return nil
			},
			func(error) {
				return
			},
		)
	}
	g.Run()
}

// 打印结果:
Go routine 3 is sleeping...
Go routine 3 is sleeping...
Go routine 3 is sleeping...
Go routine 3 is closed
Go routine 2 is closed
Go routine 1 is closed
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

oklog run包使用 的相关文章

随机推荐

  • 论文分享——Bottom-Up and Top-Down Attention for Image Captioning and Visual Question Answering

    文章目录 文章简介1 背景介绍研究背景概念介绍问题描述IC与VQA领域的主要挑战 2 相关研究CNN 43 RNN体系架构Attention mechanismBottom Up and Top Down AttentionBottom U
  • spring mvc 源码分析之父子容器问题

    spring mvc 源码分析 spring mvc 源码分析之父子容器问题 spring mvc 源码分析前言为什么要弄两个ioc容器 xff1f 一个不可以吗存在两个容器 父容器是spring ioc容器自容器是springmvc io
  • C++11特性

    C 43 43 11已经出来很久了 xff0c 网上也早有很多优秀的C 43 43 11新特性的总结文章 xff0c 在编写本博客之前 xff0c 博主在工作和学习中学到的关于C 43 43 11方面的知识 xff0c 也得益于很多其他网友
  • CentOS 7 Squid缓存代理服务器搭建——筑梦之路

    简介 xff1a Squid 是 Linux Unix 平台下最为流行的高性能免费应用层代理服务器 xff0c 它具有权限管理灵活 性能高和效率快的特点 代理服务器可以提供文件缓存 复制和地址过滤等服务 xff0c 充分利用有限的出口带宽
  • python列表的基础操作

    python列表的操作 列表是python最为基础的数据结构 xff0c 极为重要 这话怎么理解呢 xff1f 是最常用的 xff0c 想不到其他的 xff0c 就用列表是其他数据结构的基础 xff0c 可以继承列表然后定义属于自己的数据类
  • C++正则表达式(regex_match、regex_search与regex_replace)

    前言 正则表达式是在字符串处理中常用和重要的工具 xff0c 主要用于字符串的匹配 在C 中正则表达式的使用非常方便 xff0c 但到了C 43 43 中让我有点懵逼了 xff0c 花了些时间查阅了很多资料 xff0c 下面主要会写到C 4
  • Java爬虫详解

    这是 Java 爬虫系列文章的第一篇 第一篇是关于 Java 爬虫入门内容 在该篇中我们以采集开源情报网站中的ip数据为例 需要提取的内容如下图所示 Statistics AbuseIPDB nbsp nbsp nbsp 我们需要提取图中圈
  • ubuntu安装过程

    feat 新增功能 fix 修复 bug docs 文档相关的改动 style 对代码的格式化改动 xff0c 代码逻辑并未产生任何变化 test 新增或修改测试用例 refactor 重构代码或其他优化举措 chore 项目工程方面的改动
  • SpringSecurityOAuth和Jwt

    一 SpringSecurityOAuth简介 grant type为授权模式password为密码模式 64 EnableAuthorizationServer表示定义认证服务器 64 EnableResourceServer表示定义资源
  • 无法使用ssh的可能

    1 SSH服务未启动 xff1a 请确保SSH服务在远程计算机上已经启动 在Ubuntu上 xff0c 可以通过运行以下命令来启动SSH服务 xff1a sudo service ssh start 2 防火墙阻止了SSH连接 xff1a
  • CentOS7.0 关闭防火墙

    systemctl stop firewalld service 停止firewall systemctl disable firewalld service 禁止firewall开机启动
  • 如何查看张量tensor,并将其转换为numpy数据

    在tensorflow 中一般数据都是用tensor来表示 xff0c 而在python 中一般是用numpy包 xff0c 然而有时候需要打印变量的数据 xff0c 可用以下方法来打印 xff1a 一 import tensorflow
  • 浅谈联邦学习Federated Learning

    最近人工智能 大数据领域的公众号疯狂给我推送 联邦学习 相关的文章 xff0c 使得本来并不好奇的我 xff0c 有了一丝丝揭开它神秘面纱的冲动 公众号的每篇推文写得都很好 xff0c 但同时也十分学术 xff0c 作为刚上路的我 xff0
  • 云计算中的容器技术及其实践案例

    第一章 xff1a 什么是容器技术 随着云计算和DevOps的普及 xff0c 容器技术在IT行业中越来越受到关注 容器是一种轻量级 可移植 可扩展的应用程序封装技术 xff0c 可以将应用程序及其所有依赖项打包到一个独立的可执行文件中 相
  • 小坑整理

    for range坑 问题描述 range循环的时候 xff0c 取赋值的地址 xff0c 然后保存到map中 xff0c 结果是什么样子 xff1f 这里先回想下变量是什么时候才申请内存 xff1f 只有赋值给新的变量时 xff0c 内存
  • go操作es

    TOC 前言 xff1a elasticsearch 是一个基于Lucene构建的开源的 分布式 restful接口的全文搜索引擎 es还是一个分布式的文档数据库 xff0c 其中每个字段均可被索引 xff0c 而且每个字段的数据均可被搜索
  • 9-gin使用websocket

    toc gin使用websocket Gin 框架默认不支持 websocket xff0c 可以使用 github com gorilla websocket 实现 Talk is cheap Show me the code xff0c
  • 1. 准备环境

    硬件资源 mac 12 2 1 golang 1 15 3 minikube v1 25 1 prometheus operator 0 35 1 下载地址 xff1a https github com prometheus operato
  • pprof查docker内存占用

    https zhuanlan zhihu com p 363584053 https blog csdn net u010278923 article details 78774914
  • oklog run包使用

    oklog run 包介绍 oklog run 包非常简单 xff0c 只有一个类型 xff0c 两个方法 xff0c 共 60 行代码 其中 Group 是一组 actor xff0c 通过调用 Add 方法将 actor 添加到 Gro