python3 threads in the abbreviated

Multithreading in python3
1, the advantages:
  1) the program using threads can occupy long tasks into the background to deal with.
  2) better user interface, runs fast (not absolute).
  3) waiting on some of the tasks of realization: If the user input, read and write files, send and receive network data, etc., through the use of thread can release memory alleviate excessive memory footprint issues.
2, each entry has a separate thread running, sequences and procedures performed in the order outlet. But the thread is not able to execute independently, it must exist according to the application, providing multiple execution threads controlled by the application.
3, each thread has his own set of CPU registers, called the context of the thread, the thread context reflects the status of the last run of the thread CPU registers.
4, instruction pointer and stack pointer registers are the two most important thread context register, the thread always runs in the context of the process, these addresses are used to mark the owning thread of the process address space of memory.
5, the thread can be divided into:
  Kernel threads: the operating system kernel created and destroyed.
  User threads: kernel support and do not need threads implemented in the user program.
6, thread module: Python3 provide support for threading through two standard library _thread and threading. _thread provides a low level, the original thread and a simple lock, it is compared to the threading module function is quite limited. Other methods threading module contains all the methods _thread modules, also provided:
  . 1) threading.currentThread (): returns the current thread variable.
  2) threading.enumerate (): Returns a list of running threads. Refers to the thread starts running, before the end, does not include a thread before starting and after termination.
  3) threading.activeCount (): Returns the number of running threads, and len (threading.enumerate ()) have the same result.
In addition to using the method, the threading module also provides a Thread class processing thread, Thread class provides the following methods:
  . 1) RUN (): method to represent the active threads.
  2) start (): start thread activity.
  3) join ([time]) : Wait until the thread suspended. This blocks the calling thread until the thread's join () method is called suspension - normal exit or throw an unhandled exception - or the optional timeout occurs.
  4) isAlive (): Returns the thread is active.
  5) getName (): Returns the thread name.
  6) setName (): Set the thread name.

: Create a thread using the threading module
  import threading

  myThread class (threading.Thread):
    DEF __init __ (Self, parameter 1, parameter 2, parameter ... 3):
      threading.Thread .__ the init __ (Self)
      ...
    DEF RUN (Self):
      Pass

create a new thread: here myThread () parameter with the class defined parameters are consistent
  thread1 = myThread (parameter 1, parameter 2, parameter 3 ...)
to open a new thread:
  thread1.start ()
waits for a thread to terminate
  thread1.join ()

7, thread synchronization: Lock the Thread object and can achieve a simple Rlock thread synchronization, these two objects have acquire method and release method for the data that needs to allow only one thread operation, the operation may be put between the acquire and release method.
8, thread priority queue: Python's Queue module provides synchronization, thread-safe queue class: fifoQueue, lifoQueue, PriorityQueue these queues are implemented locking primitives can be used directly in a multithreaded, you can use queues. synchronization between threads.

Principles and lock queue (lock) are basically the same: the order is a guarantee, will not cross processing, to avoid inconsistencies occur.

Look at an example:

  import queue
  import threading
  import time

  exit flag = 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 ("开启线程:" + self.name)
      process_data(self.name, self.q)
      print ("退出线程:" + self.name)

  def process_data(threadName, q):
    while not exitFlag:
      if not workQueue.empty():
        data = q.get()#线程优先队列中是没有出队函数的,这个get():获取队列,应该就算是出队的了。
        print ("%s processing %s" % (threadName, data))
      time.sleep(1)

  threadList = ["Thread-1", "Thread-2", "Thread-3"]
  nameList = ["One", "Two", "Three", "Four", "Five"]
  workQueue = queue.Queue(10)
  threads = []
  threadID = 1

  # 填充队列
  for word in nameList:
  workQueue.put(word)

  # 创建新线程
  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 ("退出主线程")

输出:

 

Guess you like

Origin www.cnblogs.com/yangrongkuan/p/12120188.html