python進階筆記 thread 和 threading模塊學習


Python通過兩個標准庫thread和threading提供對線程的支持。
thread提供了低級別的、原始的線程以及一個簡單的鎖。
threading基於Java的線程模型設計。
鎖(Lock)和條件變量(Condition)在Java中是對象的基本行為(每一個對象都自帶了鎖和條件變量),而在Python中則是獨立的對象。
start_new_thread()要求一定要有前兩個參數。所以,就算我們想要運行的函數不要參數,我們也要傳一個空的元組。

test_thread.py
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import thread
import time
from time import sleep,ctime

test_list = [5,8]
def f1():
print 'start f1 at:',ctime()
sleep(5)
print 'f1 done at:',ctime()
def f2():
print 'start f1 at:',ctime()
sleep(3)
print 'f1 done at:',ctime()
def main():
print "start:",ctime()
thread.start_new_thread(f1,())
thread.start_new_thread(f2,())
sleep(6)
print "all end:",ctime()
if __name__ == '__main__':
main()

test_threading.py
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time

exitFlag = 0

class myThread(threading.Thread):
def __init__(self,threadID,name,delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self):
print "Starting" + self.name
print_time(self.name,self.delay,5)
print "Exiting" + self.name
def print_time(threadName,delay,counter):
while counter:
try:
if exitFlag:
thread.exit()
time.sleep(delay)
print "%s:%s" % (threadName, time.ctime(time.time()))
counter -= 1
except Exception,e:
logging.info(e)
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",2)

thread1.start()
thread2.start()

print "Exiting Main Thread"

python多線程threading.Lock鎖的用法

#創建鎖
mutex = threading.Lock()
#鎖定
mutex.acquire([timeout])
#釋放
mutex.release()

test_threading_lock.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import threading
import time

class my_thread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num = num + 1
msg =self.name + 'set num to '+str(num)
print msg
mutex.release()
num = 0
mutex = threading.Lock()
def test():
for i in range(5):
t = my_thread()
t.start()
if __name__ == '__main__':
test()

python 多線程中常用到的幾個方法,鏈接地址:http://blog.chinaunix.net/uid-27571599-id-3484048.html



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM