Python基础 专题
您的位置:python > Python基础专题 > Python多线程编程
Python多线程编程
作者:--    发布时间:2019-11-20

同时运行多个线程类似于同时运行多个不同的程序,但具有以下好处 -

  • 进程内的多个线程与主线程共享相同的数据空间,因此可以比单独的进程更容易地共享信息或彼此进行通信。

  • 线程有时也被称为轻量级进程,它们不需要太多的内存开销; 它们比进程便宜。

线程有一个开始,执行顺序和终止。 它有一个指令指针,可以跟踪其上下文中当前运行的位置。

  • 它可以被抢占(中断)。
  • 当其他线程正在运行时,它可以临时保留(也称为睡眠) - 这称为让步。

有两种不同的线程 -

  • 内核线程
  • 用户线程

内核线程是操作系统的一部分,而用户空间线程未在内核中实现。

有两个模块用于支持在python 3中使用线程 -

  • _thread
  • threading

thread模块已被“不推荐”了很长一段时间。 鼓励用户使用threading模块。 因此,在python 3中,thread模块不再可用。 但是,thread模块已被重命名为“_thread”,用于python 3中的向后兼容性。

1.启动新线程

要产生/启动一个线程,需要调用thread模块中的以下方法 -

_thread.start_new_thread ( function, args[, kwargs] )

这种方法调用可以快速有效地在linux和windows中创建新的线程。

方法调用立即返回,子线程启动并使用传递的args列表调用函数。当函数返回时,线程终止。

在这里,args是一个元组的参数; 使用空的元组来调用函数表示不传递任何参数。 kwargs是关键字参数的可选字典。

示例

#!/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

当执行上述代码时,会产生以下结果 -

f:\worksp\python>python thread_start.py
thread-1: tue jun 27 03:06:09 2018
thread-2: tue jun 27 03:06:11 2018
thread-1: tue jun 27 03:06:11 2018
thread-1: tue jun 27 03:06:13 2018
thread-2: tue jun 27 03:06:15 2018
thread-1: tue jun 27 03:06:15 2018

程序进入无限循环,可通过按ctrl-c停止或退出。虽然它对于低级线程非常有效,但与较新的线程模块相比,thread模块非常有限。

2. threading模块

python 2.4中包含的较新的线程模块为线程提供了比上面讨论的线程模块更强大的高级支持。
线程模块公开了线程模块的所有方法,并提供了一些其他方法 -

  • threading.activecount() - 返回活动的线程对象的数量。
  • threading.currentthread() - 返回调用者线程控件中线程对象的数量。
  • threading.enumerate() - 返回当前处于活动状态的所有线程对象的列表。

除了这些方法之外,threading模块还有实现线程的thread类。 thread类提供的方法如下:

  • run() - run()方法是线程的入口点。
  • start() - start()方法通过调用run()方法启动一个线程。
  • join([time]) - join()等待线程终止。
  • isalive() - isalive()方法检查线程是否仍在执行。
  • getname() - getname()方法返回一个线程的名称。
  • setname() - setname()方法设置线程的名称。

3.使用threading模块创建线程

要使用threading模块实现新线程,必须执行以下操作:

  • 定义thread类的新子类。
  • 覆盖__init __(self [,args])方法添加其他参数。
  • 然后,重写run(self [,args])方法来实现线程在启动时应该执行的操作。

当创建了新的thread的子类之后,就可以创建一个实例,然后调用start()方法来调用run()方法来启动一个新的线程。

示例

#!/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-1
starting thread-2
thread-1: tue jun 27 03:19:43 2017
thread-2: tue jun 27 03:19:44 2017
thread-1: tue jun 27 03:19:44 2017
thread-1: tue jun 27 03:19:45 2017
thread-2: tue jun 27 03:19:46 2017
thread-1: tue jun 27 03:19:46 2017
thread-1: tue jun 27 03:19:47 2017
exiting thread-1
thread-2: tue jun 27 03:19:48 2017
thread-2: tue jun 27 03:19:50 2017
thread-2: tue jun 27 03:19:52 2017
exiting thread-2
exiting main thread

4.同步线程

python提供的threading模块包括一个简单易用的锁定机制,允许同步线程。 通过调用lock()方法创建一个新的锁,该方法返回新的锁。

新锁对象的acquire(blocking)方法用于强制线程同步运行。可选的blocking参数能够控制线程是否要等待获取锁定。

如果blocking设置为0,则如果无法获取锁定,则线程将立即返回0值,如果锁定已获取,则线程返回1。 如果blocking设置为1,则线程将blocking并等待锁定被释放。

新的锁定对象的release()方法用于在不再需要锁定时释放锁。

示例

#!/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-1
starting thread-2
thread-1: tue jun 27 03:51:45 2017
thread-1: tue jun 27 03:51:46 2017
thread-1: tue jun 27 03:51:47 2017
thread-2: tue jun 27 03:51:49 2017
thread-2: tue jun 27 03:51:51 2017
thread-2: tue jun 27 03:51:53 2017
exiting main thread

5.多线程优先级队列

queue模块允许创建一个新的队列对象,可以容纳特定数量的项目。 有以下方法来控制队列 -

  • get() - get()从队列中删除并返回一个项目。
  • put() - put()将项添加到队列中。
  • qsize() - qsize()返回当前队列中的项目数。
  • empty() - 如果队列为空,则empty()方法返回true; 否则返回false
  • full() - 如果队列已满,则full()方法返回true; 否则返回false

示例

#!/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-1
starting thread-2
starting thread-3
thread-3 processing one
thread-3 processing two
thread-3 processing three
thread-3 processing four
thread-3 processing five
exiting thread-1
exiting thread-2
exiting thread-3
exiting main thread

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册