欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實(shí)現(xiàn)的多線程同步與互斥鎖功能示例

 更新時(shí)間:2017年11月30日 11:47:19   作者:愛橙子的OK繃  
這篇文章主要介紹了Python實(shí)現(xiàn)的多線程同步與互斥鎖功能,涉及Python多線程及鎖機(jī)制相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python實(shí)現(xiàn)的多線程同步與互斥鎖功能。分享給大家供大家參考,具體如下:

#! /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() #實(shí)例化一個(gè)Thread對(duì)象,每個(gè)Thread對(duì)象代表著一個(gè)線程
    s.start() #通過start()方法,開始線程活動(dòng)
'''
#'''
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 #多個(gè)線程共享操作的數(shù)據(jù)
mu = threading.Lock() #創(chuàng)建一個(gè)鎖
class MyThread(threading.Thread):
  def run(self):
    global num
    time.sleep(1)
    if mu.acquire(True): #獲取鎖狀態(tài),一個(gè)線程有鎖時(shí),別的線程只能在外面等著
      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()

運(yùn)行結(jié)果:

再分別運(yùn)行注釋中的每一部分代碼:

1. 不加鎖:

2. 加鎖:

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python進(jìn)程與線程操作技巧總結(jié)》、《Python Socket編程技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論