• python threading acquire release


    线程同步

    //test.py

    import threading

    import time

    exitFlag = 0

    class myThread (threading.Thread):

        def __init__(self, threadID, name, counter):

            threading.Thread.__init__(self)

            self.threadID = threadID

            self.name = name

            self.counter = counter

        def run(self):

            print "Starting " + self.name

            threadLock.acquire()

            print_time(self.name, self.counter, 5)

            threadLock.release()

            print "Exiting " + self.name

    def print_time(threadName, delay, counter):

        while counter:

            if exitFlag:

                    #threading.Thread.exit()

                    return

            time.sleep(delay)

            print "%s: %s" % (threadName, time.ctime(time.time()))

            counter -= 1

    threadLock = threading.Lock()

    threads = []

    thread1 = myThread(1, "Thread-1", 1)

    thread2 = myThread(2, "Thread-2", 2)

    thread1.start()

    thread2.start()

    #exitFlag = 1

    threads.append(thread1)

    threads.append(thread2)

    for t in threads:

            t.join()

    print "Exiting Main Thread"

    //result

    # python test.py
    Starting Thread-1
    Starting Thread-2
    Thread-2: Wed Nov 15 18:31:53 2017
    Thread-2: Wed Nov 15 18:31:55 2017
    Thread-2: Wed Nov 15 18:31:57 2017
    Thread-2: Wed Nov 15 18:31:59 2017
    Thread-2: Wed Nov 15 18:32:01 2017
    Exiting Thread-2
    Thread-1: Wed Nov 15 18:32:02 2017
    Thread-1: Wed Nov 15 18:32:03 2017
    Thread-1: Wed Nov 15 18:32:04 2017
    Thread-1: Wed Nov 15 18:32:05 2017
    Thread-1: Wed Nov 15 18:32:06 2017
    Exiting Thread-1
    Exiting Main Thread

    Finally:

    看到没有,关键任务是大家排排队,吃果果。

    不要争,不要抢,谁先干的,就让他先干完,咋这么过瘾呢!!!:):)

  • 相关阅读:
    Oracle数据库限定特定用户 特定IP 登录
    Elasticsearch 监控
    Elasticsearch 使用:创建、插入、查询、更新、删除
    ES 的基本用法
    elasticsearch 集群管理(集群规划、集群搭建、集群管理)
    ElasticSearch 集群环境搭建,安装ElasticSearch-head插件,安装错误解决
    Greenplum 基准测试
    MySQL 计算时间差函数 TIMESTAMPDIFF、DATEDIFF
    PostgreSQL 时间函数 extract函数
    Greenplum最佳实践
  • 原文地址:https://www.cnblogs.com/woodzcl/p/7843096.html
Copyright © 2020-2023  润新知