自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

解析Python多線程編程兩種表現(xiàn)方式

移動開發(fā)
解析Python多線程編程兩種表現(xiàn)方式是本文介紹的內(nèi)容,先來看本文詳細(xì)內(nèi)容介紹。

本文介紹的是解析Python多線程編程兩種表現(xiàn)方式。Python中如果要使用線程的話,python的lib中提供了兩種方式。一種是函數(shù)式,一種是用類來包裝的線程對象。(例子已經(jīng)稍加修改)

1、調(diào)用thread模塊中的start_new_thread()函數(shù)來產(chǎn)生新的線程,請看代碼:

Python語言 : 臨時自用代碼 

  1. import time  
  2. import thread  
  3. import sys  
  4. TIMEOUT = 20 
  5. def myThread(no, interval):  
  6.     timeTotal = 0 
  7.     while True:  
  8.         if timeTotal < TIMEOUT: 
  9.             print "Thread(%d): timeTotal(%d)\n"%(no, timeTotal)  
  10.             timeTotal += interval  
  11.         else:  
  12.             print "Thread(%d) exits!\n"%no  
  13.             break  
  14. def test():  
  15.     thread.start_new_thread(myThread, (1, 2))  
  16.     thread.start_new_thread(myThread, (2, 3))  
  17. if __name__ == '__main__':  
  18.     test()  

這個是

  1. thread.start_new_thread(function,args[,kwargs]) 

函數(shù)原型,其中 function參數(shù)是你將要調(diào)用的線程函數(shù);args是講傳遞給你的線程函數(shù)的參數(shù),他必須是個tuple類型;而kwargs是可選的參數(shù)。

線 程的結(jié)束一般依靠線程函數(shù)的自然結(jié)束;也可以在線程函數(shù)中調(diào)用thread.exit(),他拋出SystemExit exception,達到退出線程的目的。

2、通過調(diào)用threading模塊繼承threading.Thread類來包裝一個線程對象。請看代碼

Python語言 : 臨時自用代碼 

  1. import threading  
  2. import time  
  3.  
  4. class MyThread(threading.Thread):  
  5.     def __init__(self, no, interval):  
  6.         threading.Thread.__init__(self)  
  7.         self.no = no  
  8.         self.interval = interval  
  9.  
  10.     def run(self):  
  11.         while self.interval > 0:  
  12.             print "ThreadObject(%d) : total time(%d)\n"%(self.no, self.interval)  
  13.             time.sleep(1)  
  14.             self.interval -1 
  15. def test():  
  16.     thread1 = MyThread(1, 10)  
  17.     thread2 = MyThread(2, 20)  
  18.     thread1.start()  
  19.     thread2.start()  
  20.     thread1.join()  
  21.     thread2.join()  
  22.  
  23. if __name__ == '__main__':  
  24.     test()  

其實thread和threading的模塊中還包含了其他的很多關(guān)于多線程編程的東西,例如鎖、定時器、獲得激活線程列表等等,請大家仔細(xì)參考 python的文檔!

小結(jié):關(guān)于解析Python多線程編程兩種表現(xiàn)方式的內(nèi)容介紹完了,希望本文對你有所幫助。

責(zé)任編輯:zhaolei 來源: 互聯(lián)網(wǎng)
相關(guān)推薦

2010-02-02 14:32:32

Python線程編程

2010-07-14 10:30:26

Perl多線程

2011-06-29 16:25:11

Qt Signal Slot

2010-07-13 14:54:15

Perl面向?qū)ο缶幊?/a>

2010-07-27 15:03:37

Flex ArrayC

2011-08-09 13:50:01

iPhone動畫UIView

2020-02-21 17:33:17

SparkKafka數(shù)據(jù)

2010-03-03 17:44:07

Python多線程

2011-03-03 10:26:04

Pureftpd

2011-08-08 14:13:47

iPhone XML NSXMLParse

2010-09-07 11:09:59

2025-01-14 00:00:00

場景線程數(shù)據(jù)

2011-08-03 16:35:10

iPhone UIView 動畫

2011-08-03 16:26:14

iPhone UIView 動畫

2009-06-25 13:43:00

Buffalo AJA

2010-10-21 16:24:18

sql server升

2021-05-27 10:57:01

TCP定時器網(wǎng)絡(luò)協(xié)議

2010-08-06 09:38:11

Flex讀取XML

2023-03-29 13:06:36

2010-04-20 15:32:20

主控負(fù)載均衡
點贊
收藏

51CTO技術(shù)棧公眾號