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
相關文章
相關標籤/搜索