Threading in Python Sugggestions - python

I am currently trying to thread two loops in python. One is currently a tkinter loop that displays the the gui I have set up, and the other is a p2p chat function. using 'import threading', defining threads and starting them individually doesn't seem to work. Any suggestions for what method I can use to get these two loops running concurrently?
The code I'm using to start the threads:
thread1 = threading.Thread(target=x.mainloop())
thread1.start()
thread2 = threading.Thread(target=root.mainloop())
thread2.start()

You need to pass the functions without calling them. As is, you're trying to call them, and pass the return value as the target for the thread; since they never return, you never launch the second thread. Try:
thread1 = threading.Thread(target=x.mainloop) # Removed call parens on target
thread1.start()
thread2 = threading.Thread(target=root.mainloop) # Removed call parens on target
thread2.start()

Related

How to terminate threads in python on raspberry pi 3?

The problem is relatively simple only that I could not find any
answer with a google search for terms:
How to terminate threads in python
How to end while loop using keyboard input in threads etc
So format of the program is this:
import everything necessary
def readingsomething():
DOING SOME WORK in a infinite while loop and sleep for 1 sec
def readingsomeotherthing():
DOING SOME WORK in a infinite while loop and sleep for 2 sec
thread1 = thread.thread(target = readingsomething)
thread2 = thread.thread(target = readingsomeotherthing)
try:
thread1.start()
thread2.start()
thread1.join()
thread2.join()
except KeyboardInterrupt:
save a file and sys.exit()
So when I run the program everything is smooth except when I
press ctrl + c it does not terminate as per keyboardInterrupt
I am losing the data collected as I am unable to save them.
Any suggestions and help will be appreciated.
You could use the synchronized queue Queue as a pipe to send a value to the thread.
It is rather unclear what you're trying to do.
You're talking about loops but I see none in your code.
Also, written like that, you will first wait for thread1 to stop, then wait for thread2 to stop, make sure it's what you want.
Put a timeout inside these 'join' calls, otherwise it prevents the listening of exceptions:
thread1.join()
becomes
thread1.join(10)
You may want to think about the changes it induces on your code.
Working Python 3 example:
from threading import Thread, Event
import time
def readingsomething(stop):
while not stop.isSet():
print('readingsomething() running')
time.sleep(1)
def readingsomeotherthing(stop):
while not stop.isSet():
print('readingsomeotherthing() running')
time.sleep(2)
if __name__ == '__main__':
stop = Event()
thread1 = Thread(target=readingsomething, args=(stop,))
thread2 = Thread(target=readingsomeotherthing, args=(stop,))
thread1.start()
thread2.start()
try:
thread1.join()
thread2.join()
except KeyboardInterrupt:
print('catched KeyboardInterrupt')
stop.set()
#save the file
print('EXIT __main__')
Tested with Python:3.4.2

Stopping threads from inside a thread [duplicate]

For every client connecting to my server I spawn a new thread, like this:
# Create a new client
c = Client(self.server.accept(), globQueue[globQueueIndex], globQueueIndex, serverQueue )
# Start it
c.start()
# And thread it
self.threads.append(c)
Now, I know I can close all the threads using this code:
# Loop through all the threads and close (join) them
for c in self.threads:
c.join()
But how can I close the thread from within that thread?
When you start a thread, it begins executing a function you give it (if you're extending threading.Thread, the function will be run()). To end the thread, just return from that function.
According to this, you can also call thread.exit(), which will throw an exception that will end the thread silently.
How about sys.exit() from the module sys.
If sys.exit() is executed from within a thread it will close that thread only.
This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?
A little late, but I use a _is_running variable to tell the thread when I want to close. It's easy to use, just implement a stop() inside your thread class.
def stop(self):
self._is_running = False
And in run() just loop on while(self._is_running)
If you want force stop your thread:
thread._Thread_stop()
For me works very good.

Why does not multi-threads save time in my Python script?

I have the following script which utilizes threading module in order to save time when doing cycle.
import threading, time, sys
def cycle(start, end):
for i in range(start, end):
pass
#########################################################
thread1 = threading.Thread(target = cycle, args=(1,1000000))
thread2 = threading.Thread(target = cycle, args=(1000001,2000000))
thread1.start()
thread2.start()
print 'start join'
thread1.join()
thread2.join()
print 'end join'
However, I found the the script cost even more time than the one without multi-threads (cycle(1, 2000000)).
What might be the reason and how can I save time?
Threads are often not useful in Python because of the global interpreter lock: only one thread can run Python code at a time.
There are cases where the GIL doesn't cause much of a bottleneck, e.g. if your threads are spending most of their time calling thread-safe native (non-Python) functions, but your program doesn't appear to be one of those cases. So even with two threads, you're basically running just one thread at a time, plus there's the overhead of two threads contending for a lock.

Main thread stuck in Python Multithreading

I have 2 simple functions:
def run(self):
# Make 20 instances of clients and start those
for i in xrange(0,20):
t = threading.Thread(target = self.run_clients_in_seperate_threads())
t.start()
and
def run_clients_in_seperate_threads(self):
print 'inside run_clients_in_seperate_threads'
client_id = self.generate_client_id()
cl = Client(client_id)
cl.start()
Here, the last line: cl.start() is an infinite loop.
I was thinking that the main thread will become free after starting the child threads, and hence will spawn 20 threads in total.
But it seems that the main thread waits after starting the 1st thread.
Can someone please explain what I'm doing wrong ?
Use target = self.run_clients_in_seperate_threads and pass self to the args parameter . The way you way you do it you invoke the method in the main thread and end up with the infinite loop there : self.run_clients_in_seperate_threads != self.run_clients_in_seperate_threads()

python threading blocks

I am trying to write a program which creates new threads in a loop, and doesn't wait for them to finish.
As I understand it if I use .start() on the thread, my main loop should just continue, and the other thread will go off and do its work at the same time
However once my new thread starts, the loop blocks until the thread completes.
Have I misunderstood how threading works in Python, or is there something stupid I'm doing?
Here is my code for creating new threads.
def MainLoop():
print 'started'
while 1:
if not workQ.empty():
newThread = threading.Thread(target=DoWorkItem(), args=())
newThread.daemon = True
newThread.start()
else:
print 'queue empty'
This calls the function and passes its result as target:
threading.Thread(target=DoWorkItem(), args=())
Lose the parentheses to pass the function object itself:
threading.Thread(target=DoWorkItem, args=())

Categories