Python解决多线程的坑
引言:由于这两天在开发电报脚本,想用Threading写一个多线程,但是死活出现There is no current event loop in thread 'Thread-1'这个错误。后来经过几十根的掉发研究发现!
这是因为,旧线程使用了 asyncio.get_event_loop() ,而此时不存在 event loop。
默认情况下,在主线程中时,若没有event loop,则 asyncio 会自动创建一个新的 event loop(参见 asyncio.get_event_loop 的文档)
而在一个其他线程中,则不会自动创建。
所以如果你运行的函数里面有调用其他模块的api,那模块的api也是用多线程的话就要使用
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
把这两句放在那个api引用的前面
比如:
import threadingimport paramiko
from paramiko.py3compat import u
def run():
lock.acquire() #修改数据前加锁
global num
num +=1
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
sshd = paramiko.SSHClient() //比如我这里调用了导入的连接SSH模块函数,就需要在上面添加那两句。就能完美运行不报错
sshd.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 允许连接不在know_hosts文件中的主机
sshd.connect("1.1.1.1",22, "root","root")
stdin, stdout, stderr = sshd.exec_command('free;ifconfig;id;df -h')
print stdout.read()
sshd.close()
print(num)
lock.release() #修改完后释放
lock=threading.Lock()
num=0
t_objs = []
for i in range(1000):
t=threading.Thread(target=run)
t.start()
t_objs.append(t)
for t in t_objs: #循环线程实例列表,等待子线程执行完毕
t.join()
print(num)
----GS小顾
评论 (0)