classLockThread(threading.Thread): defrun(self): global num # introduce global variable time.sleep(1) if mutex.acquire(timeout=1): # acquire lock (only wait 1 second) num += 1# change global variable msg = '{0}: num={1}'.format(self.name, num) print(msg) time.sleep(1) mutex.acquire() # multi-lock can be acquired mutex.release() # resource is free only after all locks are released mutex.release()
if __name__ == '__main__': # add lock to sub-thread for i inrange(5): t = LockThread() t.start()
# customize thread function classMyThread(threading.Thread): def__init__(self, name, n): super(MyThread, self).__init__() self.name = name self.n = n defrun(self): print('Current task is', self.name) while self.n > 0: self.n -= 1
if __name__ == '__main__': t1 = MyThread('Thread 1', 10000000) t2 = MyThread('Thread 2', 10000000) # main thread will not wait for sub-thread t1.setDaemon(True) # must be set before start() t2.setDaemon(True)
t1.start() t2.start()
print('Exit')
Timer
1 2 3 4 5 6 7
from threading import Timer defshow(): print("Hello world!")
classMyProcess(Process): def__init__(self, name): super(MyProcess, self).__init__() self.name = name defrun(self): print('Process name is', self.name)
if __name__ == '__main__': proc = Process(target=show, args=('Process -1',)) proc.start() proc.join() for i inrange(5): p = MyProcess('Process {0}'.format(i)) p.start()
for i inrange(5): p.join()
Pool
You do not have to create sub-processes one by one.
1 2 3 4 5 6 7 8 9 10 11 12
from multiprocessing import Pool
defshow(num): print('num: {0}'.format(num))
if __name__ == '__main__': pool = Pool(processes=4) # max concurrent process <= num of physical cores for i inrange(5): pool.apply_async(func=show, args=(i,)) print('===== apply_async =====') pool.close() # close pool after all sub-processes are finished pool.join() # main process will wait for sub-process (after close())