之前写的脚本,会出现因网络原因关闭某些线程,先构思了一个启动一个相同线程的方法
网上看了一些什么用setName方法重命名并再启动线程的方法,还是会报错
所以现在基本思路是:
因PYTHON的垃圾回收机制,关闭的线程会自动回收,所以不必担心启动太多线程而造成的内存问题。
1、把所有线程保存在一个list,把所有线程名和启动线程args存入一个dict
2、定时循环这个list,查找没启动的线程,并把这个线程从list和dict中删除
3、然后使用被删除的线程的args值再启动一个新的线程
# coding=utf-8
from ws4py.client.threadedclient import WebSocketClient
from ws4py.websocket import Heartbeat
from testscripts.httpApi import *
import time
import json
import threading
import random
class Ws(WebSocketClient):
def __init__(self, url, token2, room_id, user_id='test280'):
super().__init__(url)
self.token = token2
self.roomId = room_id
self.userId = user_id
def opened(self):
pass
def closed(self, code, reason=None):
pass
def received_message(self, message):
pass
def start(room_id, user_id):
token3 = loginById(user_id)['data']['token']
time.sleep(1)
aa = addGame(token3, room_id, user_id)
ws_url = aa['data']['socketUrl']
ws = Ws(ws_url, token3, room_id, user_id)
ws.connect()
Heartbeat(ws).run()
ws.run_forever()
if __name__ == '__main__':
userId = 'test281'
token = loginById(userId)['data']['token']
create_room = CreateRoom(token, userId).createBaiRen()
roomId = create_room['data']['roomId']
num = 0
threadingList = []
threadingDict = {}
for _ in range(99):
userId = 'test3' + str(num)
th = threading.Thread(target=start, args=(roomId, userId, ))
threadingList.append(th)
threadingDict[th.__dict__['_name']] = th.__dict__['_args']
th.start()
num += 1
while True:
for i in threadingList:
if i.is_alive() is False:
threadingList.remove(i)
result = threadingDict.pop(i.name)
th = threading.Thread(target=start, args=result)
threadingList.append(th)
threadingDict[th.__dict__['_name']] = th.__dict__['_args']
th.start()
print(th)
time.sleep(60)