python标准库中有多线程:threading包.本文分面向过程和面向对量两种方式记录一下多线程的写法:
1.面向过程:
1 # A program to simulate selling tickets in multi-thread way
2 # Written by Vamei
3
4 import threading
5 import time
6 import os
7
8 # This function could be any function to do other chores.
9 def doChore():
10 time.sleep(0.5)
11
12 # Function for each thread
13 def booth(tid):
14 global i
15 global lock
16 while True:
17 lock.acquire() # Lock; or wait if other thread is holding the lock
18 if i != 0:
19 i = i - 1 # Sell tickets
20 print(tid,':now left:',i) # Tickets left
21 doChore() # Other critical operations
22 else:
23 print("Thread_id",tid," No more tickets")
24 os._exit(0) # Exit the whole process immediately
25 lock.release() # Unblock
26 doChore() # Non-critical operations
27
28 # Start of the main function
29 i = 100 # Available ticket number
30 lock = threading.Lock() # Lock (i.e., mutex)
31
32 # Start 10 threads
33 threads = []
34 for k in range(10):
35 new_thread = threading.Thread(target=booth,args=(k,)) # Set up thread; target: the callable (function) to be run, args: the argument for the callable
36 threads.append(new_thread)
37 for t in threads: # run the thread
38 t.start()
39 for t in threads: # wait all thread end
40 t.join()
2.面向对象:
# A program to simulate selling tickets in multi-thread way
# Written by Vamei
import threading
import time
import os
# This function could be any function to do other chores.
def doChore():
time.sleep(0.5)
# Function for each thread
class BoothThread(threading.Thread):
def __init__(self, tid, monitor):
self.tid = tid
self.monitor = monitor
threading.Thread.__init__(self)
def run(self):
while True:
monitor['lock'].acquire() # Lock; or wait if other thread is holding the lock
if monitor['tick'] != 0:
monitor['tick'] = monitor['tick'] - 1 # Sell tickets
print(self.tid,':now left:',monitor['tick']) # Tickets left
doChore() # Other critical operations
else:
print("Thread_id",self.tid," No more tickets")
os._exit(0) # Exit the whole process immediately
monitor['lock'].release() # Unblock
doChore() # Non-critical operations
# Start of the main function
monitor = {'tick':100, 'lock':threading.Lock()}
# Start 10 threads
threads = []
for k in range(10):
new_thread = BoothThread(k, monitor)
threads.append(new_thread)
for t in threads: # run the thread
t.start()
for t in threads: # wait all thread end
t.join()
Ps:
python中print不是线程保护的,多线程输出的时候会乱掉,可以用sys.stdout.write()函数替换