成都创新互联网站制作重庆分公司

python中怎么实现threading线程同步

小编给大家分享一下python中怎么实现threading线程同步,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:成都网站设计、成都做网站、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的兴业网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

说明

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线程同步”有了一定的了解,如果想了解更多相关知识,欢迎关注创新互联行业资讯频道,感谢各位的阅读!


网页题目:python中怎么实现threading线程同步
URL网址:http://cxhlcq.com/article/jsdipd.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部