之前写的脚本,会出现因网络原因关闭某些线程,先构思了一个启动一个相同线程的方法
网上看了一些什么用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 test s.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):
c101 = json.dumps({
\"c\": 101,
\"data\": {
\"userId\": self.userId,
\"token\": self.token,
\"roomId\": self.roomId,
\"tableId\": \"1\",
\"location\": {
\"latitude\": \'null\',
\"longitude\": \'null\'
}
}
})
self.send(c101)
self.send(\'{\"c\":106,\"gameType\":\"BAIRENNIUNIU\"}\')
def closed(self, code, reason=None):
print(nowtime())
def received_message(self, message):
ms = json.loads(str(message))
c107 = json.dumps({
\"c\": 107,
\"data\": {
\"tableNum\": random.randint(1, 4),
\"chip\": random.randint(0, 3)
# \"chip\":3
}
})
if ms[\'c\'] == 121:
time.sleep(random.randint(3, 12))
self.send(c107)
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)
继续阅读与本文标签相同的文章
上一篇 :
面对BIM技术现存的争议,你怎么看?
-
阿里云InfluxDB技术内幕
2026-05-18栏目: 教程
-
RocketMQ 主从同步若干问题答疑
2026-05-18栏目: 教程
-
RocketMQ ACL使用指南
2026-05-18栏目: 教程
-
从事iOS开发4年,我干倒三家公司,4年开发笔记(总结)送给正在迷茫的你!
2026-05-18栏目: 教程
-
【面小易-面经12】阿里巴巴Java方向面试题汇总(含答案)
2026-05-18栏目: 教程
