美文网首页
Python Implement Worker Threads

Python Implement Worker Threads

作者: Sam_f32a | 来源:发表于2018-06-30 17:39 被阅读0次

    # Python Version: 2.7

    import time

    import threading

    import thread

    from Queue import Queue

    # Global Queue

    q = Queue()

    num_worker_threads = 2

    # worker to get item/message from the queue and process it.

    def worker(q):

            while True:

                    print("Waiting for Message ...{thread}\n".format(thread=thread.get_ident()))

                    item = q.get()

                    print("Message received...{thread}...{msg}\n".format(msg=item, thread=thread.get_ident()))

                    if item is None:

                            q.task_done()

                            print("Stop worker!")

                            break

                    do_work(item)

                    q.task_done()

    #function to process message

    def do_work(item):

            print("Processing Message ...{thread}...{msg}\n".format(msg=item, thread=thread.get_ident()))

            print("sleep 5s...")

            time.sleep(5)

            print("Message Processed...{thread}..{msg}\n".format(msg=item, thread=thread.get_ident()))

    # start worker threads

    threads = []

    for i in range(num_worker_threads):

            t=threading.Thread(target=worker, args=(q,))

            t.start()

            threads.append(t)

    # Add items to the Queue

    for item in ["AA", "BB", "CC"]:

            q.put(item)

    # Stop all workers

    for i in range(num_worker_threads):

            q.put(None)

    相关文章

      网友评论

          本文标题:Python Implement Worker Threads

          本文链接:https://www.haomeiwen.com/subject/cztxuftx.html