go 多线程并发 queue demo
原文链接:Writing worker queues, in Go
1.work.go
[root@wangjq queue]# cat work.go
package main import "time" type WorkRequest struct {
Name string
Delay time.Duration
}
2.collector.go
[root@wangjq queue]# cat collector.go
package main import (
"fmt"
"net/http"
"time"
) // A buffered channel that we can send work requests on.
var WorkQueue = make(chan WorkRequest, ) func Collector(w http.ResponseWriter, r *http.Request) {
// Make sure we can only be called with an HTTP POST request.
if r.Method != "POST" {
w.Header().Set("Allow", "POST")
w.WriteHeader(http.StatusMethodNotAllowed)
return
} // Parse the delay.
delay, err := time.ParseDuration(r.FormValue("delay"))
if err != nil {
http.Error(w, "Bad delay value: "+err.Error(), http.StatusBadRequest)
return
} // Check to make sure the delay is anywhere from 1 to 10 seconds.
if delay.Seconds() < || delay.Seconds() > {
http.Error(w, "The delay must be between 1 and 10 seconds, inclusively.", http.StatusBadRequest)
return
} // Now, we retrieve the person's name from the request.
name := r.FormValue("name") // Just do a quick bit of sanity checking to make sure the client actually provided us with a name.
if name == "" {
http.Error(w, "You must specify a name.", http.StatusBadRequest)
return
} // Now, we take the delay, and the person's name, and make a WorkRequest out of them.
work := WorkRequest{Name: name, Delay: delay} // Push the work onto the queue.
WorkQueue <- work
fmt.Println("Work request queued") // And let the user know their work request was created.
w.WriteHeader(http.StatusCreated)
return
}
3.worker.go
[root@wangjq queue]# cat worker.go
package main import (
"fmt"
"time"
) // NewWorker creates, and returns a new Worker object. Its only argument
// is a channel that the worker can add itself to whenever it is done its
// work.
func NewWorker(id int, workerQueue chan chan WorkRequest) Worker {
// Create, and return the worker.
worker := Worker{
ID: id,
Work: make(chan WorkRequest),
WorkerQueue: workerQueue,
QuitChan: make(chan bool)} return worker
} type Worker struct {
ID int
Work chan WorkRequest
WorkerQueue chan chan WorkRequest
QuitChan chan bool
} // This function "starts" the worker by starting a goroutine, that is
// an infinite "for-select" loop.
func (w *Worker) Start() {
go func() {
for {
// Add ourselves into the worker queue.
w.WorkerQueue <- w.Work select {
case work := <-w.Work:
// Receive a work request.
fmt.Printf("worker%d: Received work request, delaying for %f seconds\n", w.ID, work.Delay.Seconds()) time.Sleep(work.Delay)
fmt.Printf("worker%d: Hello, %s!\n", w.ID, work.Name) case <-w.QuitChan:
// We have been asked to stop.
fmt.Printf("worker%d stopping\n", w.ID)
return
}
}
}()
} // Stop tells the worker to stop listening for work requests.
//
// Note that the worker will only stop *after* it has finished its work.
func (w *Worker) Stop() {
go func() {
w.QuitChan <- true
}()
}
4.dispatcher.go
[root@wangjq queue]# cat dispatcher.go
package main import "fmt" var WorkerQueue chan chan WorkRequest func StartDispatcher(nworkers int) {
// First, initialize the channel we are going to but the workers' work channels into.
WorkerQueue = make(chan chan WorkRequest, nworkers) // Now, create all of our workers.
for i := ; i < nworkers; i++ {
fmt.Println("Starting worker", i+)
worker := NewWorker(i+, WorkerQueue)
worker.Start()
} go func() {
for {
select {
case work := <-WorkQueue:
fmt.Println("Received work requeust")
go func() {
worker := <-WorkerQueue fmt.Println("Dispatching work request")
worker <- work
}()
}
}
}()
}
5.main.go
[root@wangjq queue]# cat main.go
package main import (
"flag"
"fmt"
"net/http"
) var (
NWorkers = flag.Int("n", , "The number of workers to start")
HTTPAddr = flag.String("http", "127.0.0.1:8000", "Address to listen for HTTP requests on")
) func main() {
// Parse the command-line flags.
flag.Parse() // Start the dispatcher.
fmt.Println("Starting the dispatcher")
StartDispatcher(*NWorkers) // Register our collector as an HTTP handler function.
fmt.Println("Registering the collector")
http.HandleFunc("/work", Collector) // Start the HTTP server!
fmt.Println("HTTP server listening on", *HTTPAddr)
if err := http.ListenAndServe(*HTTPAddr, nil); err != nil {
fmt.Println(err.Error())
}
}
6.编译
[root@wangjq queue]# go build -o queued *.go
7.运行
[root@wangjq queue]# ./queued -n
Starting the dispatcher
Starting worker
Starting worker
Starting worker
Starting worker
Starting worker
Registering the collector
HTTP server listening on 127.0.0.1:
8.测试
[root@wangjq ~]# for i in {..}; do curl localhost:/work -d name=$USER -d delay=$(expr $i % )s; done
9.效果
[root@wangjq queue]# ./queued -n
Starting the dispatcher
Starting worker
Starting worker
Starting worker
Starting worker
Starting worker
Registering the collector
HTTP server listening on 127.0.0.1:
Work request queued
Received work requeust
Dispatching work request
worker1: Received work request, delaying for 1.000000 seconds
Work request queued
Received work requeust
Dispatching work request
worker2: Received work request, delaying for 2.000000 seconds
Work request queued
Received work requeust
Dispatching work request
worker4: Received work request, delaying for 3.000000 seconds
worker1: Hello, root!
worker2: Hello, root!
worker4: Hello, root!
go 多线程并发 queue demo的更多相关文章
- java多线程并发执行demo,主线程阻塞
其中有四个知识点我单独罗列了出来,属于多线程编程中需要知道的知识: 知识点1:X,T为泛型,为什么要用泛型,泛型和Object的区别请看:https://www.cnblogs.com/xiaoxio ...
- Python2 socket 多线程并发 ThreadingTCPServer Demo
# -*- coding:utf-8 -*- from SocketServer import TCPServer, StreamRequestHandler import traceback cla ...
- Python2 socket 多线程并发 TCPServer Demo
#coding=utf-8 import socket import threading,getopt,sys,string opts, args = getopt.getopt(sys.argv[1 ...
- 用Queue控制python多线程并发数量
python多线程如果不进行并发数量控制,在启动线程数量多到一定程度后,会造成线程无法启动的错误. 下面介绍用Queue控制多线程并发数量的方法(python3). # -*- coding: utf ...
- 多线程并发执行任务,取结果归集。终极总结:Future、FutureTask、CompletionService、CompletableFuture
目录 1.Futrue 2.FutureTask 3.CompletionService 4.CompletableFuture 5.总结 ================正文分割线========= ...
- java中并发Queue种类与各自API特点以及使用场景!
一 先说下队列 队列是一种数据结构.它有两个基本操作:在队列尾部加入一个元素,和从队列头部移除一个元素(注意不要弄混队列的头部和尾部) 就是说,队列以一种先进先出的方式管理数据,如果你试图向一个 已经 ...
- Java多线程-并发容器
Java多线程-并发容器 在Java1.5之后,通过几个并发容器类来改进同步容器类,同步容器类是通过将容器的状态串行访问,从而实现它们的线程安全的,这样做会消弱了并发性,当多个线程并发的竞争容器锁的时 ...
- python多进程并发和多线程并发和协程
为什么需要并发编程? 如果程序中包含I/O操作,程序会有很高的延迟,CPU会处于等待状态,这样会浪费系统资源,浪费时间 1.Python的并发编程分为多进程并发和多线程并发 多进程并发:运行多个独立的 ...
- Java多线程并发编程一览笔录
线程是什么? 线程是进程中独立运行的子任务. 创建线程的方式 方式一:将类声明为 Thread 的子类.该子类应重写 Thread 类的 run 方法 方式二:声明实现 Runnable 接口的类.该 ...
随机推荐
- WSGI应用程序示例
import time # WSGI允许开发者自由搭配web框架和web服务器 def app(environ,start_response): status = '200 OK' response_ ...
- Numpy数组的函数
import numpy as np # 将 0~100 10等分 x = np.arange(0,100,10) # array([ 0, 10, 20, 30, 40, 50, 60, 70, 8 ...
- Python os.lstat() 方法
概述 os.lstat() 方法用于类似 stat() 返回文件的信息,但是没有符号链接.在某些平台上,这是fstat的别名,例如 Windows.高佣联盟 www.cgewang.com 语法 ls ...
- Skill 脚本演示 ycAutoSnap.skl
https://www.cnblogs.com/yeungchie/ ycAutoSnap.skl 版图编辑中自动吸附 Path 的 "垂直线头",也可以批量对齐 Bus 走线,也 ...
- Sharding-JDBC主键生成策略
当使用分库分表等功能之后,就不能再依赖数据库自带的主键生成机制了,一方面主键ID不能重复,另外需要在新增之前就知道主键ID,才能保证ID能够均匀分布到不同的数据库或数据表中,所以要使用一个合理的主键生 ...
- 浅谈Mybatis持久化框架在Spring、SSM、SpringBoot整合的演进及简化过程
前言 最近开始了SpringBoot相关知识的学习,作为为目前比较流行.用的比较广的Spring框架,是每一个Java学习者及从业者都会接触到一个知识点.作为Spring框架项目,肯定少不了与数据库持 ...
- ASP.NET中使用Cache类来缓存页面的信息
实现 如果将数据保存在全局应用程序对象Application中,值将会在程序运行时一直存在,而我们只需要缓存一段时间. ASP.NET提供了一个Cache对象来执行对象数据的缓存. Cache对象是S ...
- sql developer连接mysql数据库
1 首先打开sql developer ,选择上方菜单,工具(tools)--->首选项,如下图 2 数据库(database)--->第三方 JDBC驱动程序 ; “添加条目”,选择m ...
- Centos7下安装一个或多个tomcat7完整
Tomcat是Apache 软件基金会(Apache Software Foundation)的Jakarta 项目中的一个核心项目,在运用中也占有大部分的市场. 根据系统下载对应的版,在线的下载地址 ...
- 面经手册 · 第2篇《数据结构,HashCode为什么使用31作为乘数?》
作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! 一.前言 在面经手册的前两篇介绍了<面试官都问我啥>和<认知自己的技术栈盲区 ...