引入線程包或者命名空間import threading
一:建立一個簡單的線程程序
import time, threading
def test():
n = 0
while n < 5:
n = n + 1
print('thread %s >>> %s' % (threading.current_thread().name, n))
time.sleep(1)
print('thread %s ended.' % threading.current_thread().name)
print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=test, name='test')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
運行結果如下:
二:多個線程中線程同步
#-*- encoding: gb2312 -*-
import string, threading, time
def thread_main(a):
global count, mutex
# 獲得線程名
threadname = threading.currentThread().getName()
for x in xrange(0, int(a)):
# 取得鎖
mutex.acquire()
count = count + 1
# 釋放鎖
mutex.release()
print(threadname, x, count)
time.sleep(1)
def main(num):
global count, mutex
threads = []
count = 1
# 創建一個鎖
mutex = threading.Lock()
# 先創建線程對象
for x in xrange(0, num):
threads.append(threading.Thread(target=thread_main, args=(10,)))
# 啟動所有線程
for t in threads:
t.start()
# 主線程中等待所有子線程退出
for t in threads:
t.join()
if __name__ == '__main__':
num = 4
# 創建4個線程
main(4)
相關理解:
如何理解join()方法:使得一個線程可以等待另一個線程執行結束后再繼續運行。這個方法還可以設定一個timeout參數, 通俗一點說就是讓當前操作join方法的線程先完成,再去執行其它流程,timeout是超時時間,比如join(1),如果過了1s線程沒有結束,線程會自動結束
如何理解線程同步:當系統中對同一個變量或方法同一時刻只允許被一個動作占用時,就要采用線程同步的方案去處理了
新聞熱點
疑難解答