Python(2.7.x)多线程的简单示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值