1. 程式人生 > >多線程模塊:thread

多線程模塊:thread

gil rt thread tar roo 官方 新的 odin 有一個 否則

thread 是一個比較低級別的模塊,官方推薦我們使用 threading 替代 thread, thread 常見用法如下:

thread.start_new_thread(function, args):開啟一個新的線程,接收兩個參數,分別為函數和該函數的參數,相當於開啟一個新的線程來執行這個函數,註意函數的參數必須是元組類型的,例子如下,開啟兩個線程同時輸出聲音和畫面

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

import time
import thread

def fun(name, n):
    for i in range(n):
        print name, i
        time.sleep(
1) thread.start_new_thread(fun, (聲音, 3)) thread.start_new_thread(fun, (畫面, 3)) time.sleep(3) # 這裏要停止幾秒,否則沒等線程執行完進程就退出了
[root@localhost ~]$ python 1.py 
畫面 0
聲音 0
畫面 1
聲音 1
畫面 2
聲音 2

thread.allocate_lock():用於創建一個鎖對象,我們可以同時開啟多個線程,但是在任意時刻只能有一個線程在解釋器運行,因此需要由全局解鎖器(GIL)控制運行哪個線程,鎖對象的常用方法如下:

多線程模塊:thread