标签:python python脚本 多线程 网络服务器 面向对象
Python主要通过标准库中的threading包来实现多线程。import threading
import time
import os
# This function could be called by any function to do other chores.
def doChore():
time.sleep(0.5)
# Function for each thread
def booth(tid):
global i
global lock
while True:
lock.acquire() # Lock; or wait if other thread is holding the lock
if i != 0:
i = i - 1 # Sell tickets
print(tid,':now left:',i) # Tickets left
doChore() # Other critical operations
else:
print("Thread_id",tid," No more tickets")
os._exit(0) # Exit the whole process immediately
lock.release() # Unblock
doChore() # Non-critical operations
# Start of the main function
i = 100 # Available ticket number
lock = threading.Lock() # Lock (i.e., mutex)
# Start 10 threads
for k in range(10):
new_thread = threading.Thread(target=booth,args=(k,)) # Set up thread; target: the callable (function) to be run, args: the argument for the callable
new_thread.start() # run the threadimport threading
import time
import os
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
for k in range(10):
new_thread = BoothThread(k, monitor)
new_thread.start()
线程可以调用对象的clear()方法来重置对象为False状态。
# 最近这几章都没怎么看太明白~~~~~
Python学习笔记16:标准库之多线程(threading包)
标签:python python脚本 多线程 网络服务器 面向对象
原文地址:http://blog.csdn.net/xufeng0991/article/details/40180817