Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从线程队列python内部停止线程_Python_Python 3.x_Multithreading_Python Multithreading - Fatal编程技术网

如何从线程队列python内部停止线程

如何从线程队列python内部停止线程,python,python-3.x,multithreading,python-multithreading,Python,Python 3.x,Multithreading,Python Multithreading,当线程与当前正在运行/正在执行的线程内的条件匹配时,我需要停止执行该线程: 下面是我的意思: 我们有从1到5的5个数字的列表 我们将它们排队,并在Run_Calc函数中处理它们以及10个线程 在Run\u Calc中,如果线程符合3 输出: 我如何做到这一点 在某些情况下,线程可能会在“谁会跑得更快”这一术语上竞争,即使它们是按顺序实例化的。 对于您的简单案例,请使用对象在特定事件上同步线程: import queue from threading import Thread, Eve

当线程与当前正在运行/正在执行的线程内的条件匹配时,我需要停止执行该线程:

下面是我的意思:

  • 我们有从1到5的5个数字的列表
  • 我们将它们排队,并在Run_Calc函数中处理它们以及10个线程
  • Run\u Calc
    中,如果线程符合
    3
  • 输出:
  • 我如何做到这一点

在某些情况下,线程可能会在“谁会跑得更快”这一术语上竞争,即使它们是按顺序实例化的。
对于您的简单案例,请使用对象在特定事件上同步线程:

import queue
from threading import Thread, Event

q = queue.Queue()
numbers = [1, 2, 3, 4, 5]

for each_num in numbers:
    q.put(each_num)


def run_calc(num, e):
    print("NO IS : {}".format(num))
    if num == 3:
        e.set()
        print("YES I WANT TO EXIT HERE and DONT WANT TO EXECUTE 4,5")


def process_thread(e):
    while not q.empty():
        if e.is_set():
            break
        num = q.get()
        run_calc(num, e)


th_list = []

e = Event()
for i in range(10):
    t = Thread(target=process_thread, args=(e,))
    th_list.append(t)
    t.start()

for th in th_list:
    th.join()
样本输出:

NO IS : 1
NO IS : 2
NO IS : 3
YES I WANT TO EXIT HERE and DONT WANT TO EXECUTE 4,5
可能重复的
import queue
from threading import Thread, Event

q = queue.Queue()
numbers = [1, 2, 3, 4, 5]

for each_num in numbers:
    q.put(each_num)


def run_calc(num, e):
    print("NO IS : {}".format(num))
    if num == 3:
        e.set()
        print("YES I WANT TO EXIT HERE and DONT WANT TO EXECUTE 4,5")


def process_thread(e):
    while not q.empty():
        if e.is_set():
            break
        num = q.get()
        run_calc(num, e)


th_list = []

e = Event()
for i in range(10):
    t = Thread(target=process_thread, args=(e,))
    th_list.append(t)
    t.start()

for th in th_list:
    th.join()
NO IS : 1
NO IS : 2
NO IS : 3
YES I WANT TO EXIT HERE and DONT WANT TO EXECUTE 4,5