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 

基于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 


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"""消费者,依次消费

 

相关文章:

  • 2022-12-23
  • 2022-01-27
  • 2021-05-25
  • 2022-12-23
  • 2021-06-04
  • 2021-12-13
  • 2022-12-23
  • 2022-01-09
猜你喜欢
  • 2021-11-04
  • 2021-11-23
  • 2021-10-19
  • 2021-12-03
相关资源
相似解决方案