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 接口的类.该 ...
随机推荐
- Python 数字数据类型
数字数据类型,包括整数.浮点数.复数和布尔类型. 整数 int 长整型(数字长度不限制):包括正数,负数,0. # 正数 num_int = 123 print(type(num_int)) # &l ...
- 2-Numpy之hstack、vstack、concatenate区别
concatenate与hstack.vstack的异同点: 都表示拼接数组,concatenate可以实现hstack和vstack的功能,只需要通过调整参数axis的值即可. 其中:v表示垂直(V ...
- PHP array_fill() 函数
------------恢复内容开始------------ 实例 用给定的键值填充数组: <?php$a1=array_fill(3,4,"blue");print_r($ ...
- PHP is_null() 函数
is_null() 函数用于检测变量是否为 NULL.高佣联盟 www.cgewang.com PHP 版本要求: PHP 4 >= 4.0.4, PHP 5, PHP 7 语法 bool is ...
- PHP xpath() 函数
定义和用法 xpath() 函数运行对 XML 文档的 XPath 查询.高佣联盟 www.cgewang.com 如果成功,该函数返回 SimpleXMLElements 对象的一个数组.如果失败, ...
- CF掉分日记 6.6 6.8
---恢复内容开始--- 写的效果依旧不好 还没写完前四题比赛就结束了 而且这些普及组的题目 我大多还是缺少简单算法的灵性 总是把问题搞复杂化. 6.5 A 第一道题非常水 简单分析发现是一个快速幂的 ...
- FFT专练
就多项式乘法这个地方不太熟 再多巩固一下. LINK:[ZJOI2014力](https://www.luogu.com.cn/problem/P3338) 把$(j-i)^2$看成一个函数 可以发现 ...
- react-ts模板/脚手架
react-ts-template 脚手架 使用 npm i -g maple-react-cli maple-react-cli init 选择模板 'react-ts-template' 输入自定 ...
- 036_go语言中的原子计数器
代码演示 package main import ( "fmt" "runtime" "sync/atomic" "time&qu ...
- NIO(一):Buffer缓冲区
一.NIO与IO: IO: 一般泛指进行input/output操作(读写操作),Java IO其核心是字符流(inputstream/outputstream)和字节流(reader/writer ...