python 多线程学习一

python线程使用有两种方法:


1.直接调用threading.Thread来构造thread对象,Thread的参数如下:
    class threading.Thread(group=None target=None name=None args=() kwargs={}) 
          group为None;
          target为线程将要执行的功能函数;
          name为线程的名字,也可以在对象构造后调用setName()来设定;
          args为tuple类型的参数,可以为多个,如果只有一个也的使用tuple的形式传入,例如(1);
          kwargs为dict类型的参数,也即位命名参数;

2.实现自己的threading.Thread的子类,需要重载__init__()和run()。

下面是两个例子:

import time
import threading

def timer(no,interval):
	cnt =0
	print threading.Thread.getName()
	while cnt<10:
		print "Thread %d,time:%s" %(no,time.ctime())
		time.sleep(interval)
		cnt+=1

def test():
	a = threading.Thread(name ="ping",target=timer,args=(1,1))
	b = threading.Thread(name ="mao",target=timer,args=(2,2))

	a.start()
	b.start()
	
	a.join()
	b.join()
if __name__ =='__main__':
	test()


 

import threading
import time
import datetime

class timer(threading.Thread):
	def __init__(self,no,interval):
		self.m_no =no
		self.m_interval = interval
		threading.Thread.__init__(self)
	
	def run(self):
		cnt =0
		while cnt<10:
			print "no %d,cnt is %d,time is %s" %(self.m_no,cnt,datetime.datetime.now())
			time.sleep(self.m_interval)
			cnt+=1

def test():
	a =timer(1,1)
	a.start()
if __name__=='__main__':
	test()
	print "Main thread exit"


 

python对于thread的管理中有两个函数:join和setDaemon

join:如在一个线程B中调用threada.join(),则threada结束后,线程B才会接着threada.join()往后运行。
使得一个线程可以等待另一个线程执行结束后再继续运行。这个方法还可以设定一个timeout参数,避免无休止的等待。因为两个线程顺序完成,看起来象一个线程,所以称为线程的合并。
setDaemon:主线程A启动了子线程B,调用b.setDaemon(True),则主线程结束时,会把子线程B也杀死。

python中得thread的一些机制和C/C++不同:在C/C++中,主线程结束后,其子线程会默认被主线程kill掉。而在python中,主线程结束后,会默认等待子线程结束后,主线程才退出。通过调用setDaemon(True),能与C/C++中得默认效果是一样的。

import threading
import time
import datetime

lock=threading.Lock()

class timer(threading.Thread):
	def __init__(self,no,interval):
		self.m_no =no
		self.m_interval =interval
		threading.Thread.__init__(self)
	
	def run(self):
		cnt =0
		while cnt<10:
			lock.acquire()
			print "no %d,cnt is %d,time is %s" %(self.m_no,cnt,datetime.datetime.now())
			lock.release()
			time.sleep(self.m_interval)
			cnt+=1

def test():
	a =timer(1,1)
	b =timer(2,2)
	#b.setDaemon(True)
	a.start()
	b.start()
if __name__=='__main__':
	test()
	print "Main thread exit"


上面的程序启动了两个线程,输出结果如下:


如果将#b.setDaemon(True)的注释去掉,则输出结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值