There are a few options for threading in python. I wont be exploring all the options here. I would simply try to make this blog entry simple, sweet and short.
There are two modules in python which provide threading capabilities - "thread" module and "threading" module. The thread module is very basic. So lets focus on the threading module
To use the threading module, all you have to do is
import threading
class mythread(threading.Thread):
def run(self):
<your code>
mythread().start()
mythread().start()
This will create 2 threads running <your code>
That was quick right. Now lets see some basic stuff like Thread Naming, Thread isAlive and join which is used in most threading environments...
Naming a thread:
import threading
class mythread(threading.Thread):
def run(self):
print 'my name is ', self.getName()
foo = mythread()
foo.setName('Foo')
foo.start()
bar = mythread()
bar.setName('Bar')
bar.start()
mythread().start()
Run the program:
$ python threadname.py
And see the output
my name is Foo
my name is Bar
my name is Thread-3
Checking if the thread is still alive:
import threading
import time
class mythread(threading.Thread):
def run(self):
print 'my name is ', self.getName()
class aliveth(threading.Thread):
def run(self):
time.sleep(10)
print 'my name is ', self.getName()
myt = mythread()
myt.setName('mythread')
myt.start()
if myt.isAlive():
print 'myt is alive'
else:
print 'myt is dead'
alt = aliveth()
alt.setName('aliveth')
alt.start()
if alt.isAlive():
print 'alt is alive'
else:
print 'alt is dead'
And check the output
my name is mythread
myt is dead
alt is alive
my name is aliveth
Joining threads:
You can use the thread.join() method to make a thread wait for another thread
import threading
import time
class ThreadOne ( threading.Thread ):
def run ( self ):
print 'Thread', self.getName(), 'started.'
print self.getName(), ': sleeping '
time.sleep ( 5 )
print 'Thread', self.getName(), 'ended.'
class ThreadTwo ( threading.Thread ):
def run ( self ):
print 'Thread', self.getName(), 'started.'
print self.getName(), ': waiting for ', thingOne.getName()
thingOne.join()
print 'Thread', self.getName(), 'ended.'
class ThreadThree (threading.Thread):
def run(self):
print 'Thread', self.getName(), 'started'
print self.getName(),': Not waiting for any other thread'
print 'Thread', self.getName(), 'ended.'
thingOne = ThreadOne()
thingOne.start()
thingTwo = ThreadTwo()
thingTwo.start()
thingThree = ThreadThree()
thingThree.start()
And check the output
Thread Thread-1 started.
Thread-1 : sleeping
Thread Thread-2 started.
Thread-2 : waiting for Thread-1
Thread Thread-3 started
Thread-3 : Not waiting for any other thread
Thread Thread-3 ended.
Thread Thread-1 ended.
Thread Thread-2 ended.
This covers most of the stuff for programming threads in python. We will look into thread synchronization issues some other time.
No comments:
Post a Comment