gpt4 book ai didi

python - 多线程Python退出

转载 作者:太空宇宙 更新时间:2023-11-03 18:22:53 25 4
gpt4 key购买 nike

我有一个 API,我想创建一个客户端来从互联网发送/接收数据,所以我使用了一个线程,这样我的 api 就不会因为阻塞命令而卡住。在我的线程中,我在写入/读取数据时循环。问题是,在 1 个循环程序退出后,我不知道为什么。

这是我的线程类

class WorkerThread(Thread):
"""Worker Thread Class."""
def __init__(self):
"""Init Worker Thread Class."""
Thread.__init__(self)
self._want_abort = 0
# This starts the thread running on creation, but you could
# also make the GUI thread responsible for calling this
self.start()

def run(self):
while(1):
if self._want_abort:
# Use a result of None to acknowledge the abort (of
# course you can use whatever you'd like or even
# a separate event type)
wx.PostEvent(ResultEvent(None))
return
Socket_ID=OPEN_CLIENT(str('184.106.153.149'), 3000, 80, SOCKET_STREAM)

WRITE(Socket_ID, 123, len(123))
time.sleep(0.5)
test = READ(Socket_ID)
if 'on' in test:
SET_IO(1,1)
if 'off' in test:
SET_IO(1,0)

time.sleep(1)
CLOSE(Socket_ID)
time.sleep(10)


def abort(self):
"""abort worker thread."""
# Method for use by main thread to signal an abort
self._want_abort = 1

触发复选框事件后,我在主函数中调用它:

def receive_data(self, event):
if self.get_cmd == 0:

self.get_cmd = 1
self.worker = WorkerThread(self)

else:
self.get_cmd = 0
self.worker.abort()

我从这里看到了Thread类:http://wiki.wxpython.org/LongRunningTasks

如果我使用这个,客户端服务器之间的 I/O 正常,但 API 被卡住

def receive_data(self, event):
if self.get_cmd == 0:

self.get_cmd = 1
self.worker = WorkerThread(self)
self.worker.join()

else:
self.get_cmd = 0
self.worker.abort()

好吧,这是另一个循环 3-4 次然后崩溃的方法:

def receive_data(self, event):

if self.get_cmd == 0:
self.thingspeak = threading.Thread(target=recv_data_thingspeak, args = (self.talkback_field.GetValue(),))
self.thingspeak.start()

else:
self.receive_bt.SetValue(True)



def recv_data_thingspeak(queue):

Socket_ID =OPEN_CLIENT(str('184.106.153.149'), 3000, 80, SOCKET_TYPE_STREAM)
while(1):

request = "GET /apps/thinghttp/send_request?api_key=" + queue + " HTTP/1.1\r\n"
request += "Host: api.thingspeak.com\r\n\r\n"

WRITE(Socket_ID, 123, len(123))
time.sleep(1)
test = READ(Socket_ID)
if 'on' in test:
SET_IO(1,1)
if 'off' in test:
SET_IO(1,0)

time.sleep(10)

CLOSE(Socket_ID)

最佳答案

多线程可能会造成困惑。例如,在第一批代码中,父 htread 设置为 (workerthread)._want_abort。然而这个标志只存在于父进程中,而不存在于工作进程中,因此这种类型的信号不起作用。

通常,多线程程序的工作方式是在父级中创建一个Queue(或Event等),然后创建一堆工作人员 - 为每个工作人员提供对队列。然后,当父线程或工作线程使用队列时,所有线程都会看到结果。你不能用列表或其他“原始”对象来做到这一点;队列有魔力,多个线程可以修改它,并且其他线程会收到通知

下面我们启动三个 worker ,稍等一下,然后通知他们全部死亡。我们通过在父级中创建一个 Event 并与每个工作人员共享来实现此目的。

import time
from threading import *

class WorkerThread(Thread):
def __init__(self, die_flag, *args, **kw):
super(WorkerThread,self).__init__(*args, **kw)
self.die_flag = die_flag

def run(self):
for num in range(3):
if self.die_flag.is_set():
print "{}: bye".format(
current_thread().name
)
return
print "{}: num={}".format(
current_thread().name, num,
)
time.sleep(1)

flag = Event()

print 'STARTING THREADS'
WorkerThread(name='whiskey', die_flag=flag).start()
WorkerThread(name='syrup', die_flag=flag).start()
WorkerThread(name='bitters', die_flag=flag).start()

print '\nRELAXING'
time.sleep(2)

print '\nTELL WORKERS TO DIE'
flag.set()

print '\nWAITING FOR WORKERS'
for thread in enumerate():
if thread != current_thread():
print thread.name,':',
thread.join()
print 'joined'

print '\nDONE'

示例运行:

STARTING THREADS
whiskey: num=0
syrup: num=0
bitters: num=0

RELAXING
syrup: num=1
whiskey: num=1
bitters: num=1
syrup: num=2
bitters: num=2

TELL WORKERS TO DIE
whiskey: num=2

WAITING FOR WORKERS
whiskey : joined
bitters : joined
syrup : joined

DONE

关于python - 多线程Python退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23781952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com