Threading an Infinite Loop - python

def check_incoming_messages_to_client(incoming_chat_messages,uri_str, kill_threads_subscript):
global kill_threads
messaging = Pyro4.Proxy(uri_str)
while(TRUE):
if(messaging.get_connection() == 'yes'):
msg = messaging.read_messages_to_client()
if (msg):
incoming_chat_messages.insert(END, msg)
if(kill_threads[kill_threads_subscript]):
print('break loop')
break
print('start')
t1 = Thread(target=check_incoming_messages_to_client(incoming_chat_messages[length-1],uri_str, kill_threads_subscript))
t1.setDaemon(True)
t1.start()
print('end')
The code above only print start and not end. That means it was stuck in the infinite loop, which must not be because it was threaded. How will I fix it?

Thread(target=check_incoming_messages_to_client(incoming_chat_messages[length-1],uri_str, kill_threads_subscript)) calls your function, then passes the result as the target (except since it never ends, no result ever materializes, and you never even construct the Thread).
You want to pass the function uncalled, and the args separately so the thread calls it when it runs, rather than the main thread running it before the worker thread even launches:
t1 = Thread(target=check_incoming_messages_to_client,
args=(incoming_chat_messages[length-1], uri_str, kill_threads_subscript))

Related

How to terminate a loop early in in a thread?

I have a loop which makes a get request to a webservice to fetch data and do some stuff, but I want to 'manually' terminate the thread/event, which I achieved with the following example:
from threading import Event
exit = Event()
if external_condition():
exit.set()
for _ in range(mins):
fetch_data_and_do_stuff()
exit.wait(10) #wait 10 seconds
With that, the only thing that terminates it's the sleep time between loops. How can I also kill the loop so it doesn't keep running until it gets to the last iteration?
nvm i've solved it like this
from threading import Event
exit = Event()
if external_condition():
exit.set()
for _ in range(mins):
fetch_data_and_do_stuff()
if exit.wait(10):
break
the condition returns true when killed and also sleeps the 10 seconds, so it works
you have 2 options ,
kill the thread or process entirely
or making the loop's boolean false. going that way
you could use a global variable in this way: [Python 3.7] , run it to see
from threading import Thread
from time import sleep
global glob
glob=True
def threaded_function():
while glob:
print("\n [Thread] this thread is running until main function halts this")
sleep(0.8)
if __name__ == "__main__":
thread = Thread(target = threaded_function, args = ())
thread.start()
for i in range(4,0,-1):
print("\n [Main] thread will be terminated in "+str(i)+" seconds")
sleep(1)
glob=False
while True:
print("[Main] program is over")
sleep(1)

How can I exit thread in python

Hi guy I am writing a socket programming in python and using multithreading but I have one problem when I want to exit a program It seem like I can not exit a running thread.
picture of my code
def create_workers():
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work)
t.daemon = True # End the Thread
t.start()
def work():
while True:
x = queue.get()
if x == 1:
create_socket()
bind_socket()
accept_connections()
if x == 2:
start_turtle()
break
queue.task_done()
the function create_workers are running two thread and targeting function work but I don't really know to terminate it after I break a while loop in function work
Use a threading.Event instance as a flag that you set just before work ends, and check if it is set at the start of each iteration of the infinite loop.
If your work function is more complicated, with multiple return statements, you could chuck the event.set() call into the finally block of a try statement.
threading.Event is thread-safe.
As pointed out by user2357112 supports Monica, making the threads daemonic doesn't make sense, so I've removed that line.
def create_workers():
event = threading.Event()
for _ in range(NUMBER_OF_THREADS):
t = threading.Thread(target=work, args=(event,))
t.start()
def work(event):
while True:
if event.is_set():
return
x = queue.get()
if x == 1:
create_socket()
bind_socket()
accept_connections()
if x == 2:
start_turtle()
break
queue.task_done()
event.set()
you can use python-worker (link)
from worker import abort_all_thread
## your running code
abort_all_thread() # this will kill any active threads

Why the queue still joining after I called task_done()?

Python3.6
First I put some items in a queue, then start a thread and called join() of the queue in the main thread, then called get() in the thread loop, when the size of queue == 0, I called task_done() and break loop and exit from the thread. But the join() method still blocked in the main thread. I can not figure out what`s wrong.
Below is the code
Thanks
import queue
import threading
def worker(work_queue):
while True:
if work_queue.empty():
print("Task 1 Over!")
work_queue.task_done()
break
else:
_ = work_queue.get()
print(work_queue.qsize())
# do actual work
def main():
work_queue = queue.Queue()
for i in range(10):
work_queue.put("Item %d" % (i + 1))
t = threading.Thread(target=worker, args=(work_queue, ))
t.setDaemon(True)
t.start()
print("Main Thread 1")
work_queue.join()
print("Main Thread 2")
t.join()
print("Finish!")
if __name__ == "__main__":
main()
task_done should be called for each work item which is dequeued and processed, not once the queue is entirely empty. (There'd be no reason for that-- the queue already knows when it's empty.) join() will block until task_done has been called as many times as put was called.
So:
def worker(work_queue):
while True:
if work_queue.empty():
print("Task 1 Over!")
break
else:
_ = work_queue.get()
print(work_queue.qsize())
# do actual work
Note that it's weird for a worker to exit as soon as it sees an empty queue. Normally it would get() with blocking, and only exit when it got a "time to exit" work item out of the queue.

Python threading.Timer not waiting before executing function

I have thrown together a quick threading test:
import threading
def test():
print "it don't work"
while True:
threading.Timer(1, test).start()
It runs test, but it doesn't wait. What's wrong?
In each loop iteration, you start a new thread. Therefore you will reach the limit of allowed thread and you will get an exception : can't start new thread.
while True:
threading.Timer(1, test).start()
You can add global flag and wait until the function is executed - You should use time.sleep to avoid busy waiting.
a = False
def test():
global a
print("hallo")
a = True
threading.Timer(10, test).start()
while not a:
time.sleep(1)
print('done')

Threading an endless while loop in Python 2

I'm not sure why this does not work. The thread starts as soon as it is defined and seems to not be in an actual thread... Maybe I'm missing something.
import threading
import time
def endless_loop1():
while True:
print('EndlessLoop1:'+str(time.time()))
time.sleep(2)
def endless_loop2():
while True:
print('EndlessLoop2:'+str(time.time()))
time.sleep(1)
print('Here1')
t1 = threading.Thread(name='t1', target=endless_loop1(), daemon=True)
print('Here2')
t2 = threading.Thread(name='t2', target=endless_loop2(), daemon=True)
print('Here3')
t1.start()
print('Here4')
t2.start()
Outputs:
Here1
EndlessLoop1:1446675282.8
EndlessLoop1:1446675284.8
EndlessLoop1:1446675286.81
You need to give target= a callable object.
target=endless_loop1()
Here you're actually calling endless_loop1(), so it gets executed in your main thread right away. What you want to do is:
target=endless_loop1
which passes your Thread the function object so it can call it itself.
Also, daemon isn't actually an init parameter, you need to set it separately before calling start:
t1 = threading.Thread(name='t1', target=endless_loop1)
t1.daemon = True

Categories

Resources