Python线程使用

一般创建threading.Thread的子类来包装一个线程对象

import threading
import time
class timer(threading.thread):
	def __init__(self,num,interval):
		thredaing.thread__init__(self)
		self.thread_num = num
		self.interval = interval
		self.thread_stop = False
	def run(self):
		while not self.thread_stop:
			print "Thread:%d, Time: %s\n" %(self.thread_num, time.ctime())
			time.sleep(self.interval)
	def stop(self):
		self.thread_stop = True
def test():
	thread1 = timer(1,1)
	thread1 = timer(2,2)
	thread1.start()
	thread2.start()
	time.sleep(10)
	thread1.stop()
	thread2.stop()
	return
if __name__=='__main__':
	test()
线程安全的问题:

如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。或者说:一个类或者程序所提供的接口对于线程来说是原子操作或者多个线程之间的切换不会导致该接口的执行结果存在二义性,也就是说我们不用考虑同步的问题。

若有多个线程同时执行写操作,一般都需要考虑线程同步,否则就可能影响线程安全。

Queue模块实现了一个支持多producer和多consumer的FIFO队列。当共享信息需要安全的在多线程之间交换时,Queue非常有用。

import random
import threading
import time
from Queue import Queue
class Producer(threading.Thread):
	def __init__(self, t_name, queue):
		threading.Thread.__init__(self, name=t_name)
		self.data=queue
	def run(self):
		for i in range(5):
			print "%s: %s is producing %d to the queue!\n" %(time.ctime(), self.getName(), i)
			self.data.put(i)
			time.sleep(random.randrange(10)/5)
		print "%s: %s finished!" %(time.ctime(), self.getName())
class Consumer(threading.Thread):  
	def __init__(self, t_name, queue):  
		threading.Thread.__init__(self, name=t_name)  
		self.data=queue  
	def run(self):
		for i in range(5):  
			val = self.data.get()  
			print "%s: %s is consuming. %d in the queue is consumed!\n" %(time.ctime(), self.getName(), val)  
			time.sleep(random.randrange(10))  
		print "%s: %s finished!" %(time.ctime(), self.getName())
	def main():
		queue = Queue()  
		producer = Producer('Pro.', queue)  
		consumer = Consumer('Con.', queue)  
		producer.start()  
		consumer.start()  
		producer.join()  
		consumer.join()  
		print 'All threads terminate!'  
if __name__ == '__main__':  
        main()

put( item[, block[, timeout]])
Queue的put方法是从队尾加入数据,如果可选参数block为true,线程被block,直到队列空出一个数据单元。反之,如果block参数为false,item被立即加入到空闲数据单元中,如果没有空闲数据单元,Full exception被抛出。

get( item[, block[, timeout]])

Queue的get方法是从队首取数据,如果block参数为true,线程被block,直到队列中有数据。反之,如果block参数为false,队列中的数据被立即取出。如果此时没有可取数据,Empty exception也会被抛出。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值