python关闭子线程_python多线程,个别线程关闭后重启的方法

之前写的脚本,会出现因网络原因关闭某些线程,先构思了一个启动一个相同线程的方法

网上看了一些什么用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):

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值