• Python多线程编程


    thread模块

    #!/usr/bin/python3
    
    import _thread
    import time
    
    # Define a function for the thread
    def print_time( threadName, delay):
       count = 0
       while count < 5:
          time.sleep(delay)
          count += 1
          print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
    
    # Create two threads as follows
    try:
       _thread.start_new_thread( print_time, ("Thread-1", 2, ) )
       _thread.start_new_thread( print_time, ("Thread-2", 4, ) )
    except:
       print ("Error: unable to start thread")
    
    while 1:
       pass

    输出

    Thread-1: Wed Dec 26 14:43:54 2018
    Thread-2: Wed Dec 26 14:43:56 2018
    Thread-1: Wed Dec 26 14:43:56 2018
    Thread-1: Wed Dec 26 14:43:58 2018
    Thread-2: Wed Dec 26 14:44:00 2018
    Thread-1: Wed Dec 26 14:44:00 2018
    Thread-1: Wed Dec 26 14:44:02 2018
    Thread-2: Wed Dec 26 14:44:04 2018
    Thread-2: Wed Dec 26 14:44:08 2018
    Thread-2: Wed Dec 26 14:44:12 2018

    threading模块

    #!/usr/bin/python3
    
    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)
          print_time(self.name, self.counter, 5)
          print ("Exiting " + self.name)
    
    def print_time(threadName, delay, counter):
       while counter:
          if exitFlag:
             threadName.exit()
          time.sleep(delay)
          print ("%s: %s" % (threadName, time.ctime(time.time())))
          counter -= 1
    
    # Create new threads
    thread1 = MyThread(1, "Thread-1", 1)
    thread2 = MyThread(2, "Thread-2", 2)
    
    # Start new Threads
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print ("Exiting Main Thread")

    输出

    Starting Thread-2Starting Thread-1
    
    Thread-1: Wed Dec 26 14:52:50 2018
    Thread-2: Wed Dec 26 14:52:51 2018Thread-1: Wed Dec 26 14:52:51 2018
    
    Thread-1: Wed Dec 26 14:52:52 2018
    Thread-2: Wed Dec 26 14:52:53 2018
    Thread-1: Wed Dec 26 14:52:54 2018
    Thread-1: Wed Dec 26 14:52:55 2018
    Exiting Thread-1
    Thread-2: Wed Dec 26 14:52:56 2018
    Thread-2: Wed Dec 26 14:52:58 2018
    Thread-2: Wed Dec 26 14:53:00 2018
    Exiting Thread-2
    Exiting Main Thread

    同步线程

    #!/usr/bin/python3
    # save file : MyThread2.py
    import threading
    import time
    
    class MyThread2 (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)
          # Get lock to synchronize threads
          threadLock.acquire()
          print_time(self.name, self.counter, 3)
          # Free lock to release next thread
          threadLock.release()
    
    def print_time(threadName, delay, counter):
       while counter:
          time.sleep(delay)
          print ("%s: %s" % (threadName, time.ctime(time.time())))
          counter -= 1
    
    threadLock = threading.Lock()
    threads = []
    
    # Create new threads
    thread1 = MyThread2(1, "Thread-1", 1)
    thread2 = MyThread2(2, "Thread-2", 2)
    
    # Start new Threads
    thread1.start()
    thread2.start()
    
    # Add threads to thread list
    threads.append(thread1)
    threads.append(thread2)
    
    # Wait for all threads to complete
    for t in threads:
       t.join()
    print ("Exiting Main Thread")

    输出

    Starting Thread-1Starting Thread-2
    
    Thread-1: Wed Dec 26 14:54:58 2018
    Thread-1: Wed Dec 26 14:55:00 2018
    Thread-1: Wed Dec 26 14:55:01 2018
    Thread-2: Wed Dec 26 14:55:03 2018
    Thread-2: Wed Dec 26 14:55:05 2018
    Thread-2: Wed Dec 26 14:55:07 2018
    Exiting Main Thread

    多线程优先级队列

    #!/usr/bin/python3
    #coding=utf-8
    
    import queue
    import threading
    import time
    
    exitFlag = 0
    
    class MyQueue (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:
          queueLock.acquire()
          if not workQueue.empty():
             data = q.get()
             queueLock.release()
             print ("%s processing %s" % (threadName, data))
          else:
             queueLock.release()
             time.sleep(1)
    
    threadList = ["Thread-1", "Thread-2", "Thread-3"]
    nameList = ["One", "Two", "Three", "Four", "Five"]
    queueLock = threading.Lock()
    workQueue = queue.Queue(10)
    threads = []
    threadID = 1
    
    # Create new threads
    for tName in threadList:
       thread = MyQueue(threadID, tName, workQueue)
       thread.start()
       threads.append(thread)
       threadID += 1
    
    # Fill the queue
    queueLock.acquire()
    for word in nameList:
       workQueue.put(word)
    queueLock.release()
    
    # Wait for queue to empty
    while not workQueue.empty():
       pass
    
    # Notify threads it's time to exit
    exitFlag = 1
    
    # Wait for all threads to complete
    for t in threads:
       t.join()
    print ("Exiting Main Thread")

    输出

    Starting Thread-1Starting Thread-3Starting Thread-2
    
    
    Thread-3 processing One
    Thread-1 processing TwoThread-2 processing Three
    
    Thread-1 processing FourThread-3 processing FiveExiting Thread-2
    
    
    Exiting Thread-1Exiting Thread-3
    
    Exiting Main Thread

  • 相关阅读:
    js循环遍历弹框,先弹出第一个之后逐步弹出第二个。。
    js获取字符串的字节长度
    tomcat启动报错:Address already in use: JVM_Bind
    自整理的jquery.Validate验证表达式
    jerichotab 初始化页面显示tab页中的第一个
    POST提交大量数据,导致后面数据丢失
    IDEA启动时自动报Plugin Error错误
    apiCloud检出代码出现以下图示错误:
    javascript的一些在IE下不支持的函数小结
    The Nature of Recognition
  • 原文地址:https://www.cnblogs.com/sea-stream/p/10179175.html
Copyright © 2020-2023  润新知