zoukankan      html  css  js  c++  java
  • 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:

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

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

  • 相关阅读:
    P5362 [SDOI2019]连续子序列 思维题
    P5360 [SDOI2019]世界地图 虚树+最小生成树
    P4565 [CTSC2018]暴力写挂 边分治+虚树
    BZOJ2870. 最长道路tree 并查集/边分治
    P4103 [HEOI2014]大工程 虚树
    P4220 [WC2018]通道 虚树+边分治
    P3261 [JLOI2015]城池攻占 可并堆
    积水问题
    23. 合并K个排序链表
    21. 合并两个有序链表
  • 原文地址:https://www.cnblogs.com/woodzcl/p/7843096.html
Copyright © 2011-2022 走看看