源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python实现的多线程同步与互斥锁功能示例

  • 时间:2020-08-19 20:25 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要: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()

运行结果: [img]http://files.jb51.net/file_images/article/201711/20171130120232977.png?2017103012259[/img] 再分别运行注释中的每一部分代码: 1. 不加锁: [img]http://files.jb51.net/file_images/article/201711/20171130120310880.png?2017103012329[/img] 2. 加锁: [img]http://files.jb51.net/file_images/article/201711/20171130120341020.png?2017103012356[/img] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/878.htm]Python进程与线程操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部