gpt4 book ai didi

python - 在 Python 中给事件线程一个唯一的编号

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

我正在对一个 API 进行多线程处理,我想为每个线程提供一个唯一的 ID,以便我可以在程序完成后根据索引处理响应。

这是我当前正在使用的代码。问题是 .getName() 不是唯一的。当线程被杀死时,标识符可以被回收。

有什么解决办法吗?

def get_Data(q):
send = q.get()
while True:
api = op.API()
api_response['Thread_id'].append(threading.currentThread().getName())
response_api = api.Get(send, "json")
api_response['query_response'].append(response_api)
q.task_done()

def threading_0SM(request):
q = Queue(maxsize=0)
if len(chunk_request)<=16:
num_threads = len(request)
else: num_threads = 16
for i in range(num_threads):
worker = Thread(target=get_Data, args=(q,))
worker.setDaemon(True)
worker.start()
for place in request:
q.put(place)
q.join()

最佳答案

创建线程时可以设置线程名称。我喜欢使用 itertools.count 来生成程序唯一的数字,因为它是线程安全的。这里我用它来创建唯一的线程名称。您可以更改格式以满足您的需要。

import itertools

# returns unique number on each next(unique_id)
unique_id = itertools.count()

def unique_thread_id():
return "mythread-" + str(next(unique_id))

def get_Data(q):
send = q.get()
while True:
api = op.API()
api_response['Thread_id'].append(threading.currentThread().getName())
response_api = api.Get(send, "json")
api_response['query_response'].append(response_api)
q.task_done()

def threading_0SM(request):
q = Queue(maxsize=0)
if len(chunk_request)<=16:
num_threads = len(request)
else:
num_threads = 16
for i in range(num_threads):
worker = Thread(target=get_Data, name=unique_thread_id(), args=(q,))
worker.setDaemon(True)
worker.start()
for place in request:
q.put(place)
q.join()

关于python - 在 Python 中给事件线程一个唯一的编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42006849/

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