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()
安装threadpool包
如果脚本无法启动,可能是没有threadpool包,可以去官网下载对应的threadpool
离线安装包进行安装,可能需要另行安装setuptools
,也可以直接在点击这里下载安装。
安装
- 解压
setuptools
安装包,进入目录,输入python setup.py install
进行安装 - 解压
threadpool
安装包,进入目录,输入python setup.py install
进行安装