python進階筆記 thread 和 threading模組學習,pythonthreading

來源:互聯網
上載者:User

python進階筆記 thread 和 threading模組學習,pythonthreading

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



 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.