当前位置:   article > 正文

python实现多线程发送网络请求——基础模板_macropython 多线程网络发送

macropython 多线程网络发送

python实现多线程基础模板

python实现多线程的方式有很多种,其中有一种比较好用的是使用threadpool线程池,它可以使用多线程的方式自动调动线程任务,具体模板如下:

import socket
import time
import threadpool

send_host = '192.168.211.20'
send_port = 514
sleep_sec = 1
package_num = 1000

# thread configure
thread_num = 40
# socket configure
address = (send_host, send_port)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# get localhostname
hostname = socket.gethostname()
# get local ip
local_ip = socket.gethostbyname(hostname)

def hello(num):
        print num
        msg = local_ip + ' %s ' % num + str(time.localtime())
        s.sendto(msg, address)

pool = threadpool.ThreadPool(thread_num)
func_var = [x for x in range(package_num)]
requests = threadpool.makeRequests(hello, func_var)
[pool.putRequest(req) for req in requests]
pool.wait()
s.close()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31

安装threadpool包

如果脚本无法启动,可能是没有threadpool包,可以去官网下载对应的threadpool离线安装包进行安装,可能需要另行安装setuptools,也可以直接在点击这里下载安装。

安装

  • 解压setuptools安装包,进入目录,输入python setup.py install进行安装
  • 解压threadpool安装包,进入目录,输入python setup.py install进行安装
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/172441
推荐阅读
相关标签
  

闽ICP备14008679号