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++)中,你是否如此这般的用对用巧了,比如这里的线程和队列

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

  • 相关阅读:
    当公有云Azure拥抱Docker容器技术
    .NET AJAX实例
    漫谈Ajax在.Net中的使用
    .NET运用AJAX 总结及其实例
    Excel自动从身份证中提取生日、性别、年龄
    ASP.NET 与 Ajax 的实现方式
    windows下编辑器Emacs的安装与配置
    2013.10.26工作Fighting(1)
    Jquery操作下拉框(DropDownList)实现取值赋值
    js调用后台,后台调用前台等方法总结
  • 原文地址:https://www.cnblogs.com/woodzcl/p/7843380.html
Copyright © 2011-2022 走看看