zoukankan      html  css  js  c++  java
  • python queue

    python中的队列,自带有同步锁原语,可以直接用来同步线程的执行,前提是把需要处理的数据放入队列中,然后各个线程独立从队列中取出数据处理

    //test.py

    import Queue

    import threading

    import time

    exitFlag = 0

    class myThread (threading.Thread):

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

            threading.Thread.__init__(self)

            self.threadID = threadID

            self.name = name

            self.q = q

        def run(self):

            print "Starting " + self.name

            process_data(self.name, self.q)

            print "Exiting " + self.name

    def process_data(threadName, q):

        while not exitFlag:

            if not workQueue.empty():

                data = q.get()

                print "%s processing %s" % (threadName, data)

            time.sleep(1)

    workQueue = Queue.LifoQueue(10)

    nameList = ["One", "Two", "Three", "Four", "Five"]

    for word in nameList:

        workQueue.put(word)

    threads = []

    threadID = 1

    threadList = ["Thread-1", "Thread-2", "Thread-3"]

    for tName in threadList:

        thread = myThread(threadID, tName, workQueue)

        thread.start()

        threads.append(thread)

        threadID += 1

    while not workQueue.empty():

        pass

    exitFlag = 1

    for t in threads:

        t.join()

    print "Exiting Main Thread"

    //result

    # python test.py
    Starting Thread-1
    Thread-1 processing Five
    Starting Thread-2
    Thread-2 processing Four
    Starting Thread-3
    Thread-3 processing Three
    Thread-1 processing Two
    Thread-2 processing One
    Exiting Thread-1
    Exiting Thread-2
    Exiting Thread-3
    Exiting Main Thread

    Finally:

    学习新语言的目的有两个

    1. 看看所谓的新语言都新在哪里了

    2. 回头看看古代语言(C/C++)中,你是否如此这般的用对用巧了,比如这里的线程和队列

    所谓,“签进的同时也是离不开后退”,就是这个道理

  • 相关阅读:
    JQuery实现页面跳转
    CSS中让背景图片居中且不平铺
    C#后台将string="23.00"转换成int类型
    BootStrap的一些基本语法
    CSS实现文字阴影的效果
    BootStrap自定义轮播图播放速度
    BootStrap 轮播插件(carousel)支持左右手势滑动的方法(三种)
    C#常用快捷键
    jQuery hover() 方法
    鼠标移动有尾巴
  • 原文地址:https://www.cnblogs.com/woodzcl/p/7843380.html
Copyright © 2011-2022 走看看