Suganth
Suganth

Reputation: 35

How to run a thread endlessly in python?

I have two threads A and B. The solution that I wish to achieve is, thread A should run endlessly consuming some events from a broker. Thread B must get activated only when there are a specific number of messages consumed, let's say 10. Thread A must run endlessly consuming messages and thread B must get activated when thread A gets 10 messages and perform an action and die, and start again when the next set of 10 messages comes in. The way I tried to work this is:

def threadA():
    #an action

def threadB():
    #an action

readThread.start()
sleep(10)
emailThread.start()

readThread.join()
emailThread.join()

By this way, the threads ends once a single loop ends. And also I didn't add the logic for starting the thread B after it gets 10 messages, which is also the part that I'm not able to achieve.

Upvotes: 0

Views: 2246

Answers (1)

Desty
Desty

Reputation: 337

while True: must be present inside a thread to use it endlessly. And in order to execute B when thread A has been executed 10 times, a queue or deque that can exchange data between threads must be used.(The use of global variables is not recommended, and it is recommended to use deque rather than queue.) Finally, a thread can only be started once, so it's a good idea to keep running unless you're declaring a new thread. Therefore, threadB also puts while True:. (It is always recommended to use daemon=True for threads that run endlessly with while True: to reduce memory wastage.)

import threading
from collections import deque

def threadA(dqu):
    count = 0
    while True:
        if count == 10:
            dqu.append('do B')
            count = 0
        #an action
        count += 1

def threadB(dqu):
    while True:
        if dqu:
            msg = dqu.popleft()
            if msg == 'do B':
                #an action

dequeAB = deque()
readThread = threading.Thread(target=threadA, args=(dequeAB,), daemon=True)
emailThread = threading.Thread(target=threadB, args=(dequeAB,), daemon=True)
readThread.start()
emailThread.start()
while True:
    pass

Upvotes: 2

Related Questions