python線程鎖(thread)學習樣本_python

來源:互聯網
上載者:User

複製代碼 代碼如下:

# encoding: UTF-8
import thread
import time

# 一個用於線上程中執行的函數
def func():
    for i in range(5):
        print 'func'
        time.sleep(1)

    # 結束當前線程
    # 這個方法與thread.exit_thread()等價
    thread.exit() # 當func返回時,線程同樣會結束

# 啟動一個線程,線程立即開始運行
# 這個方法與thread.start_new_thread()等價
# 第一個參數是方法,第二個參數是方法的參數
thread.start_new(func, ()) # 方法沒有參數時需要傳入空tuple

# 建立一個鎖(LockType,不能直接執行個體化)
# 這個方法與thread.allocate_lock()等價
lock = thread.allocate()

# 判斷鎖是鎖定狀態還是釋放狀態
print lock.locked()

# 鎖通常用於控制對共用資源的訪問
count = 0

# 獲得鎖,成功獲得鎖定後返回True
# 可選的timeout參數不填時將一直阻塞直到獲得鎖定
# 否則逾時後將返回False
if lock.acquire():
    count += 1

    # 釋放鎖
    lock.release()

# thread模組提供的線程都將在主線程結束後同時結束
time.sleep(6)

thread 模組提供的其他方法:
thread.interrupt_main(): 在其他線程中終止主線程。
thread.get_ident(): 獲得一個代表當前線程的魔法數字,常用於從一個字典中獲得線程相關的資料。這個數字本身沒有任何含義,並且當線程結束後會被新線程複用。

thread還提供了一個ThreadLocal類用於管理線程相關的資料,名為 thread._local,threading中引用了這個類。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.