Python線程的使用有兩種:基於thread模塊的start_new_thread方法和基於threading模塊的Thread類。
1. 基於thread模塊的start_new_thread方法:
import thread
from time import sleep
from random import randint
def display(name, count):
if count > 1:
print "Now, %s has %d apples.\n" % (name, count),
elif count == 1:
print "Now, %s has only one apple.\n" % name,
else:
print "Now, %s has not any apples.\n" % name,
def eat_apple(name, count):
display(name, count)
while count > 0:
print "%s eats an apple.\n" % name,
count -= 1
display(name, count)
sleep(randint(1, 3))
try:
thread.start_new_thread(eat_apple, ("Huey", 3) )
thread.start_new_thread(eat_apple, ("Sugar", 5) )
except Exception, e:
print "Thread Error\n",
基於thread模塊的start_new_thread方法已經不推薦使用了,在IDLE中這段代碼可以正確運行,在其他環境下可能會報如下錯誤:Unhandled exception in thread started by
sys.excepthook is missing
lost sys.stderr
原因:啓動線程之後,須確保主線程等待所有子線程返回結果後再退出,如果主線程比子線程早結束,無論其子線程是否是後臺線程,都將會中斷,拋出這個異常 。
2. 基於threading模塊的Thread類:
from threading import Thread
from time import sleep
from random import randint
def display(name, count):
if count > 1:
print "Now, %s has %d apples.\n" % (name, count),
elif count == 1:
print "Now, %s has only an apple.\n" % name,
else:
print "Now, %s has not any apples.\n" % name,
def eat_apple(name, count):
display(name, count)
while count > 0:
print "%s eats an apple.\n" % name,
count -= 1
display(name, count)
sleep(randint(1, 3))
class MyThread(Thread):
"""docstring for MyThread"""
def __init__(self, name, count):
super(MyThread, self).__init__()
self.name = name
self.count = count
def run(self):
eat_apple(self.name, self.count)
huey = MyThread("Huey", 3)
sugar = MyThread("Sugar", 5)
huey.start()
sugar.start()
3. 線程同步問題:
# encoding: utf-8
from threading import Thread
from threading import Lock
from time import sleep
from random import randint
# 倉庫有十個槽位
storehouse = [0] * 10
# 線程鎖
lock = Lock()
class Producer(Thread):
u"""生產者,依次往倉庫裏的十個槽位生產產品"""
def __init__(self):
super(Producer, self).__init__()
def run(self):
print "Producer starts producing...\n",
x = 0
while x < len(storehouse):
# 獲取鎖
lock.acquire()
print "Producer is producing the No.%d product.\n" % x,
storehouse[x] = 1
print "Now, the storehouse is %s\n" % storehouse,
# 釋放鎖
lock.release()
x += 1
sleep(randint(1, 3))
print "Producer has produced all the products!\n",
class Consumer(Thread):
u"""消費者,依次消費倉庫裏十個槽位的產品,如果槽位還沒有商品,則等待生產者生產"""
def __init__(self):
super(Consumer, self).__init__()
def run(self):
print "Consumer starts consuming...\n",
x = 0
while x < len(storehouse):
print "Consumer wants to consume a product...\n",
# 獲取鎖
lock.acquire()
if storehouse[x] <= 0:
print "There are not any products, the consumer waits.\n",
else:
print "Consumer is consuming the No.%d product.\n" % x,
storehouse[x] = -1
print "Now, the storehouse is %s\n" % storehouse,
x += 1
# 釋放鎖
lock.release()
sleep(randint(1, 3))
print "Consumer has consumed all the products!\n",
print "Originally, the storehouse is ", storehouse
producer = Producer()
consumer = Consumer()
producer.start()
consumer.start()
# 阻塞線程,等待其他線程結束
producer.join()
consumer.join()
print "Finally, the storehouse is ", storehouse