Arbazz Hussain
Arbazz Hussain

Reputation: 1932

How do i stop threading from inside of thread queue python

I'm in a situation where I need to stop executing a thread when it matches a condition inside of current running/executing thread:

Here's the example what i mean:

import threading,queue

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

for each_num in numbers:
    q.put(each_num)

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

def ProcessThreading():
    while not q.empty():
        get_number = q.get()
        Run_Calc(get_number)

th_list = []
for i in range(10):
    t = threading.Thread(target=ProcessThreading)
    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
NO IS : 4
NO IS : 5

Upvotes: 1

Views: 555

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

In some cases threads may compete in terms "who will race more quickly" even if they were instantiated sequentially.
For your simple case use threading.Event object to synchronize threads on particular event:

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()

Sample output:

NO IS : 1
NO IS : 2
NO IS : 3
YES I WANT TO EXIT HERE and DONT WANT TO EXECUTE 4,5

Upvotes: 1

Related Questions