Search code examples
pythonpython-3.xmultithreadingpython-multithreading

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:

  • We have list of 5 numbers from 1 to 5.
  • We queued them & processing them along with10 Number of Thread in Run_Calc function.
  • in Run_Calc i want my thread to stop if it matches a condition of 3
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()
  • OUTPUT:
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
  • How do I achieve it?

Solution

  • 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