golang如何正确关闭计时器
go如何实现并发安全的优先级队列

go实现Event事件

妙音 posted @ 2021年5月16日 21:12 in golang , 1146 阅读
 

描述

 
go协程之间用通道通信,如何将它改造成事件形式。
 
 

需求描述

 
以下是我的需求
 
e := NewEvent()
//协程1等待结果, 10是等待时间
e.Wait(10)
//协程2发送结果
e.Send(xxxx)
 

原理

 
原理比较简单,不描述了
 

示例

package common

import (
	"go.uber.org/zap"
	"sync"
	"time"
)

var NOT_USED interface{} = struct{}{}

func NewEvent() *Event {
	e := &Event{
		log: zap.S(),
	}
	e.Reset()
	return e
}

type Event struct{
	waiters  sync.Map
	log *zap.SugaredLogger
}

func (e *Event) Wait(timeout time.Duration) interface{}{
	ticker := time.NewTicker(time.Second*timeout)
	defer ticker.Stop()

	resultChan := make(chan interface{}, 1)
	e.waiters.Store(resultChan, true)

	select{
	case result := <- resultChan:
		if result == NOT_USED{
			return nil
		}
		return result
	case <- ticker.C:
		close(resultChan)
	}

	e.waiters.Delete(resultChan)
	return nil
}

func (e *Event) Send(result interface{}){
	e.waiters.Range(func(k, v interface{})bool{
		resultChan := k.(chan interface{})
		select{
		case resultChan <- result:
			e.waiters.Delete(resultChan)
		default:
			e.log.Warnf("Event.Send %p resultChan=%d, result=%v", e, len(resultChan), result)
		}
		return true
	})
}

func (e *Event) Reset(){
	e.waiters.Range(func(k, v interface{})bool{
		resultChan := k.(chan interface{})
		resultChan <- NOT_USED
		e.waiters.Delete(resultChan)
		return true
	})
}
 
 
 
Avatar_small
saad 说:
2023年6月20日 02:26

Browse a wide variety of Vellum Wrap Wedding Invitations. Customize your wedding invitations with vellum wraps with in-stock wedding invitations that ship fast. Vellum Wedding Invitations

Avatar_small
saad 说:
2023年6月22日 09:02

In this blog post, we will explore arborists important responsibilities and contributions in urban tree care. From tree pruning to disease.. published by The Real Tree Masters

Avatar_small
glamcode 说:
2023年7月01日 21:02

Great blog and article to read and visit, each and every nook of the article is well written, I have book mark it. Keep on writing it , regarding glam code home salon service.

Avatar_small
saad 说:
2023年7月02日 02:46

Certified Specialist in Periodontics. Dr. Mansur Roy has taken extensive post graduate training in Periodontics, Dental Implants and sedation. He is also certified by the College of BC to perform intravenous conscious sedation. Periodontics

Avatar_small
saad 说:
2023年7月02日 22:43

VIS Mountain is a full service market company delivering ranking results for Businesses. While many of our Customers are in healthcare. We have dedicated teams to work on all businesses such as law, services, car dealerships, and etc. From web design, website building, SEO optimization, local google ranking, geo tagging, voice search listing, we do it all. voip

Avatar_small
saad 说:
2023年7月03日 10:28

Transforming spoken words into written text effortlessly, transcription of audio by text brings clarity and accessibility to communication in the digital age. transcrição de audio para texto

Avatar_small
saad 说:
2023年7月05日 08:58

สมัครบาคาร่า เว็บตรง มั่นคงปลอดภัย ระบบออโต้ 100% สมัครบาคาร่า กับเราใครเล่นแล้วได้เงินกลับบ้านทุกคน ได้กลับน้อยมากแต่ได้เงินกลับบ้านแน่ๆ มักจะเสียน้อยกว่าได้แน่นอน บาคาร่า เว็บเราไม่เคยทำให้ใครผิดหวังในการเสียเงิน เป็นเว็บที่ดีจริงๆ ดีต่อคนเล่นอีกด้วย ในบาคาร่ามีเพลงให้ฟังเบาๆผ่อนคลายอีกต่างหาก ไม่เหมือนเว็บใครแน่นอนการันตีได้เลย เว็บบาคาร่า แตกต่างไม่เหมือนใคร เพื่อไม่อยากให้คนเล่นนั้นเครียดมากเกินไป อาจจะทำให้เป็นโรคซึมเศร้าได้ อยากให้คนเล่นได้มีความสุขกับการเล่นบาคาร่า บาคาร่าของเราเล่นง่ายแน่นอนไม่ต้องกังวลว่าจะไม่ได้เงินกลับบ้านได้ชัวร์ๆเลยแน่นอน จะได้มากได้น้อยได้อยู่แน่ๆ สมัครบาคาร่า

Avatar_small
saad 说:
2023年7月21日 09:01

Masajes relajantes, masajes deportivos, masaje tailandes. Para caballeros. servicio a domicilio en Lima. masajes a domicilio

Avatar_small
saad 说:
2023年8月03日 03:00

Ebyte is a national high-tech enterprise specializing in the research and development of wireless modules and industrial IoT terminals. Independently developed and produced products include LoRa / WiFi Wireless Module / Bluetooth / ZigBee wireless modules , 4G networking equipment, Ether net modules, NB-IoT data transmission terminals, industrial IoT LoRaWAN Gateway

Avatar_small
saad 说:
2023年8月10日 05:30

Effortlessly המרת אודיו לטקסט. Amplify content reach, searchability, and comprehension by transcribing spoken material. Embrace technology's role in transforming communication המרת אודיו לטקסט

Avatar_small
saad 说:
2023年8月12日 08:10

Restore your smile with dental implants in Hamburg! Expert solutions for seamless teeth replacement. Regain confidence in your grin. Zahnimplantat Hamburg

Avatar_small
saad 说:
2023年8月30日 21:21

Fast and easy online tool to detect AI generated content and plagiarism in any text, web page or document. Check if AI wrote

Avatar_small
saad 说:
2023年10月04日 03:16

Our team of licensed and experienced recovery professionals combine proven clinical and medical care to ensure your loved one is provided with the attention, care, and tools to live a fruitful sober life. We provide a variety of therapeutic recovery techniques as every individual requires a unique curriculum to address their challenges and begin their own recovery journey. Teen Recovery

Avatar_small
saad 说:
2023年10月18日 05:50

Welcome to Kitty Cat Cattery, we dedicate our lives to the breeding of munchkin cat for sale and Scottish fold munchkin for sale for any home Munchkin cat for sale

Avatar_small
saad 说:
2023年10月31日 00:47

B2B lead generation in less than 24 hours. lead flow

Avatar_small
saad 说:
2023年11月06日 08:24

Strangercam.com is a dynamic platform that offers a free cam chat service, connecting individuals with strangers globally for video chats. With a user-friendly interface and features like gender and country filters, it fosters engaging, real-time interactions. Whether you're looking to make new friends, find a date, or simply have a casual chat, Strangercam provides a safe, exciting environment for users to explore new conversations and form meaningful connections. free cam chat

Avatar_small
saad 说:
2023年11月07日 05:27 Al-Ahliyya Amman University (AAU) is the first private university in Jordan to be a pioneer of private education providing academic services since 1990. AAU has been accorded institutional and programmatic accreditation and is also a member of the International Association of Universities Events
Avatar_small
saad 说:
2023年11月07日 12:06

Embracing the beauty of nature with our top-notch tree services!

Avatar_small
saad 说:
2023年11月13日 03:30

Totobet adalah link live totobet login online link alternatif livetotobet terbaru lengkap dan terpercaya rasakan sensasi bermain di situs toto bet nomor satu dengan beragam bonus sensational totobet

Avatar_small
saad 说:
2023年12月01日 01:04 Meet our adorable Munchkin cat, ready to bring endless joy to your home! This little furball is not just a pet, but a purr-fect companion with its playful antics and sweet disposition. Our Munchkin is looking for a loving forever home, where it can shower you with affection and charm. Don't miss the chance to make this cutie a part of your family! DM for more details and bring home a bundle of furry happiness. Munchkin cat for sale
Avatar_small
saad 说:
2023年12月02日 07:32

Ontdek gemoedsrust met Ajax-alarmsystemen! Verken online een reeks opties en pakketten. Koop moeiteloos en geniet van installatieondersteuning. Uw veiligheid, onze prioriteit! Ajax alarm

Avatar_small
saad 说:
2023年12月15日 01:53

Electrical panel upgrade. Is it time to upgrade your electrical panel? We discuss reasons why homeowners get new electrical panels upgrades. Electrical Panel

Avatar_small
saad 说:
2023年12月31日 04:06

Köp marijuana online på vår Utopia Med Apotek hemsida. Högkvalitativa cannabisprodukter till överkomliga priser levererade i Sverige. Göra en beställning! Gorilla-lim

Avatar_small
saad 说:
2024年1月03日 05:30

Learn various techniques with the Certified Ethical Hacking V12 Course in Pune | SevenMentor from professional hackers from the industry. Enroll now Ethical Hacking Course in Pune

Avatar_small
saad 说:
2024年1月04日 05:49

Need a painting company? Groovy Hues of South Denver, CO, offers residential and commercial services to paint your dreams into reality. Call for a free estimate! castle rock painters

Avatar_small
saad 说:
2024年1月09日 06:39

GTB Components Ltd is the leading powder metal parts manufacturer aims to produce the best quality ferrous and stainless steel sintered components which fully conform to our customers’ total requirements, at a competitive price. The Company has a Global customer base supplying the Automotive, Building Products and Home/Leisure Industries. heat treatment services near me

Avatar_small
saad 说:
2024年1月10日 04:58 Elements Workshop is hosting the world's first recurring Mechanical Keyboard Design Competition. Elements Workshop will help winners of MKDC bring their designs to group buy (GB) custom keyboard
Avatar_small
saad 说:
2024年1月12日 05:55

Köp receptbelagd medicin online utan recept i Post Meds Pharmacy. Vi har de bästa priserna. Beställ medicin online receptfria läkemedel nu! meds nätapotek

Avatar_small
saad 说:
2024年1月21日 07:34

Koop medicijnen in onze online apotheek Buehler Apotheek. Hoogwaardig medicijn tegen betaalbare prijzen met snelle levering in Nederland. Plaats nu een bestelling! ketamines kopen

Avatar_small
saad 说:
2024年1月26日 06:21 We are Committed to providing our customers with a seamless shopping experience, we ensure fast and reliable shipping and dummy vapes near me dummy vapes
Avatar_small
saad 说:
2024年1月26日 06:34

Introducing the beautiful Breeze Pro Flavors Disposable Vape - the ultimate portable vape device for your daily routine. With its compact. breeze pro flavors

Avatar_small
saad 说:
2024年2月04日 05:58

Situs Judi Bola Sbobet Online Terpercaya Sbobet88 bola Indonesia sbobet

Avatar_small
saad 说:
2024年2月12日 23:47

ABI Resources is a prominent Connecticut-based organization dedicated to offering comprehensive support services to individuals with acquired brain injuries (ABI). This organization is recognized for its specialized programs, including the ABI Waiver Program and the Money Follows the Person (MFP) Program, which aim to facilitate community and home-based care options. ABI Resources provides a range of services such as life skills training, cognitive behavioral therapy, care management, and outpatient therapy support, all tailored to meet the unique needs of those living with brain injuries. By focusing on areas such as brain injury awareness, home modifications, personal care assistance, and neuro knowledge, ABI Resources aims to enhance the quality of life for individuals with ABIs, advocating for their needs and supporting their rehabilitation journey. Their mission encompasses compassion and advocacy, ensuring that clients receive personalized and effective care management to thrive in their communities. Entertainment for TBI patients and families CT

Avatar_small
saad 说:
2024年2月29日 23:42

With a stylish home in a peaceful location, yet close to shops, schools and the motorway network – modern living doesn’t get much better than this. homes for sale in Ormskirk

Avatar_small
saad 说:
2024年4月01日 04:51

Maxanim supplies Gentaur lab reagents in USA and Europe. Our Elisa kits are for research use. We manufacture custom recombinant proteins, plasmids, design primers, rabbit plyclonal and mouse monoclonal antibodies. mouse monoclonal antibodies

Avatar_small
saad 说:
2024年4月03日 11:12

Buy online cheapest flight ticket on major airlines. Division of Skyline Travel Company, IATA and ARC approved travel advisor since 1986 in Dallas. 214-310-1411 Indian Travel agent in Dallas

Avatar_small
saad 说:
2024年4月08日 03:13

Our Stories Sauce bars, a fast-growing brand, aim to bring more joy an excitement to users and is committed to making the world a better Sauce bars

Avatar_small
Dr.Billa 说:
2024年5月25日 09:02

קידום אתרים בגוגל , פיתוח אתרים בגוגל באמצעות שופיפיי וורדפרס יצירת סרטוני אנימציה לעסקים סרטונים לעסקים ועוד פיתוח אתרים בשופיפיי


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter