python线程同步锁_Python实现的多线程同步与互斥锁功能示例
本文實例講述了Python實現的多線程同步與互斥鎖功能。分享給大家供大家參考,具體如下:
#! /usr/bin/env python
#coding=utf-8
import threading
import time
'''
#1、不加鎖
num = 0
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1) #一定要sleep!!!
num = num + 1
msg = self.name + ' num is ---- ' + str(num)
print msg
def test():
for i in range(10):
s = MyThread() #實例化一個Thread對象,每個Thread對象代表著一個線程
s.start() #通過start()方法,開始線程活動
'''
#'''
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = self.name+' @ '+str(i)
print msg
def test():
for i in range(5):
t = MyThread()
t.start()
#'''
'''
#2、加鎖
num = 0 #多個線程共享操作的數據
mu = threading.Lock() #創建一個鎖
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mu.acquire(True): #獲取鎖狀態,一個線程有鎖時,別的線程只能在外面等著
num = num + 1
msg = self.name + ' num is ---- ' + str(num)
print msg
mu.release() #釋放鎖
def test():
for i in range(10):
s = MyThread()
s.start()
'''
if __name__ == '__main__':
test()
運行結果:
再分別運行注釋中的每一部分代碼:
1. 不加鎖:
2. 加鎖:
希望本文所述對大家Python程序設計有所幫助。
總結
以上是生活随笔為你收集整理的python线程同步锁_Python实现的多线程同步与互斥锁功能示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python开发的前景_python开发
- 下一篇: clodeblocks debug断点调