资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

pythonthreading线程同步怎么实现

本篇内容主要讲解“python threading线程同步怎么实现”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python threading线程同步怎么实现”吧!

开福ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

说明

1、threading模块具有实现锁定的内置功能,允许同步线程。

为了防止数据损坏或丢失,需要锁定来控制共享资源的访问。

2、可以调用Lock()方法来应用锁,它新的锁对象。

可以调用锁对象的获取(阻塞)方法来强制线程同步运行。

实例

#Python 多线程示例来演示锁定。
#1. 使用 threading.Thread 类定义子类。
#2. 实例化子类并触发线程。
#3. 在线程的 run 方法中实现锁。
 
import threading
import datetime
 
exitFlag = 0
 
class myThread (threading.Thread):
    def __init__(self, name, counter):
        threading.Thread.__init__(self)
        self.threadID = counter
        self.name = name
        self.counter = counter
    def run(self):
        print("\nStarting " + self.name)
        # 获取锁同步线程
        threadLock.acquire()
        print_date(self.name, self.counter)
        # 为下一个线程释放锁
        threadLock.release()
        print("Exiting " + self.name)
 
def print_date(threadName, counter):
    datefields = []
    today = datetime.date.today()
    datefields.append(today)
    print("{}[{}]: {}".format( threadName, counter, datefields[0] ))
 
threadLock = threading.Lock()
threads = []
 
# 创建新线程
thread1 = myThread("Thread", 1)
thread2 = myThread("Thread", 2)
 
# 启动新线程
thread1.start()
thread2.start()
 
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
 
# 等待所有线程完成
for thread in threads:
    thread.join()
 
print("\nExiting the Program!!!")

到此,相信大家对“python threading线程同步怎么实现”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


网站题目:pythonthreading线程同步怎么实现
浏览地址:http://cdkjz.cn/article/gcgjcj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

大客户专线   成都:13518219792   座机:028-86922220