• 技术文章 >Python技术 >Python基础教程

    python threading线程同步如何实现

    小妮浅浅小妮浅浅2021-08-30 09:22:46原创2132

    说明

    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学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python threading
    品易云
    上一篇:python threading实现线程的过程 下一篇:python聚类算法是什么

    相关文章推荐

    • python中Prewitt算子如何理解• python中Sobel算子是什么• python中Sobel算子如何使用• python中Laplacian算子如何使用• python中Laplacian算子是什么• python输入函数input的使用• python控制语句的两大分类• python编写程序的常见错误• python用户如何自定义异常• python thread模块创建线程• python threading实现线程的过程

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网