multithreading - Creating threads from the same class but with different methods connected in Python -
classes should generic, right? i've got example of multithreading using threading module, overrides run method, in fact class can create thread connected print_time method. how can make thread of same class, connected different method, example print_time_2?
#!/usr/bin/python import threading import time exitflag = 0 class mythread (threading.thread): def __init__(self, threadid, name, counter): threading.thread.__init__(self) self.threadid = threadid self.name = name self.counter = counter def run(self): print "starting " + self.name print_time(self.name, self.counter, 5) print "exiting " + self.name def print_time(threadname, delay, counter): while counter: if exitflag: thread.exit() time.sleep(delay) print "%s: %s" % (threadname, time.ctime(time.time())) counter -= 1 def print_time_2(threadname): while true: print "its me, %s" % (threadname) # create new threads thread1 = mythread(1, "thread-1", 1) thread2 = mythread(2, "thread-2", 2) #how connect thread print_time_2 # start new threads thread1.start() thread2.start() print "exiting main thread"
instead of creating own thread class, can import thread
class threading
module , invoke functions (and specify arguments necessary)
example -
from threading import thread def print_time(threadname, delay, counter): while counter: if exitflag: thread.exit() time.sleep(delay) print "%s: %s" % (threadname, time.ctime(time.time())) counter -= 1 def print_time_2(threadname): while true: print "its me, %s" % (threadname) t1 = thread(target=print_time, args=(1, "thread-1", 1) ) t2 = thread(target=print_time_2, args=("thread-2" , ) ) t1.start() t2.start()
document python threading class - https://docs.python.org/2/library/threading.html
and yes, if args consists of 1 argument, need last ',' given in example.
Comments
Post a Comment