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:

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

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

  • 相关阅读:
    JavaScript中创建对象的几种模式
    Vue学习5:条件渲染
    Vue学习4:class与style绑定
    Vue学习3:计算属性computed与监听器
    Vue学习2:模板语法
    普通递归与优化递归
    new操作符具体干了什么呢?
    各种形式存放token
    用es6的Array.reduce()方法计算一个字符串中每个字符出现的次数
    ES6 对象的解构赋值
  • 原文地址:https://www.cnblogs.com/woodzcl/p/7843096.html
Copyright © 2011-2022 走看看