• 多线程模块


    多线程模块
    Python的多线程模块有两种实现方法
    函数,线程类
    一【函数】
    调用thread模块中的start_new_thread()函数来创建线程,以线程函数的形式告诉线程该做什么

    #!/usr/bin/python
    import thread
    def f(name):
    	print "this is "+name
    if __name__=="__main__":
    	thread.start_new_thread(f,("mimi",))
    	while 1:
    		pass
    

    二【线程类】
    调用threading模块,创建threading.Thread的子类来得到自定义线程类

    [root@server0 thread]# cat 2.py 
    #!/usr/bin/python
    import threading
    class Th(threading.Thread):
    	def __init__(self,name):
    		threading.Thread.__init__(self)
    		self.t_name=name
    	def run(self): 重写run函数,线程默认从此函数开始执行
    		print "this is "+self.t_name
    if __name__=="__main__":
    	thread1=Th("thread1")
    	thread1.start() start()函数启动线程,自动执行run函数
    	#thread1.join() 
    	print "main thread is over
    

    threading.Thread类的可继承函数;
    getName()获得线程对象名称
    setName()设置线程对象名称
    Join()等待调用的线程结束之后再运行之后的命令

    三【线程锁】

    Threading提供线程锁,可实现线程同步

    #!/usr/bin/python
    import time
    import threading
    class Th(threading.Thread):
    	def __init__(self,thread_name):
    		threading.Thread.__init__(self)
    		self.setName(thread_name)
    	def run(self):
    		threadLock.acquire()   获得锁以后再运行
    		print  "this is thread"+self.getName()
    		for i in range(3):
    			time.sleep(1)
    			print str(i)
    		print self.getName()+"is over"
    		threadLock.release()释放锁
    if __name__=="__main__":
    	threadLock=threading.Lock()
    	thread1=Th("Thread1")
    	thread2=Th("Thread2")
    	thread1.start()
    	thread2.start()
    
  • 相关阅读:
    10月日常练习1题目描述
    普及组复赛历年考题
    9.3练习题7 子串乘积正负分类 题解
    9.3练习题6 旅行 题解
    9.3练习题4 语句解析 题解
    9.3练习题5 单词覆盖还原 题解
    unity
    矩阵快速幂
    点权和
    SCOI生日快乐
  • 原文地址:https://www.cnblogs.com/hanfei-1005/p/5708160.html
Copyright © 2020-2023  润新知