首页 > 文章列表 > 如何在Python中使用线程进行编程

如何在Python中使用线程进行编程

Python 线程 编程
243 2023-08-21

线程有时被称为轻量级进程,它们不需要太多的内存开销;它们比进程更便宜。一个线程有一个开始,一个执行序列和一个结束。

有两个模块支持在Python3中使用线程 -

  • _thread − 在Python 3中已弃用

  • 多线程 − 在Python 2.4中引入

线程模块

Python 2.4中包含的较新的线程模块提供了比thread模块更强大、更高级的线程支持。

线程模块公开了线程模块的所有方法,并提供了一些额外的方法 -

  • threading.activeCount() − 返回活动的线程对象的数量。

  • threading.currentThread() − 返回调用者线程控制中的线程对象数量。

  • threading.enumerate() − 返回当前活动的所有线程对象的列表。

线程模块具有实现线程的Thread类。Thread类提供的方法如下:

  • run() − run() 方法是线程的入口点。

  • start() − start() 方法通过调用 run 方法来启动一个线程。

  • join([time]) − join()方法会等待线程终止。

  • isAlive() − isAlive()方法用于检查线程是否仍在执行。

  • getName() − getName()方法返回线程的名称。

  • setName() − setName()方法设置线程的名称。

编写线程

Python提供的线程模块包含了一个简单易用的锁机制,可以用来同步线程。通过调用Lock()方法来创建一个新的锁,该方法会返回新的锁。

新锁对象的acquire(blocking)方法用于强制线程同步运行。可选的blocking参数允许您控制线程是否等待获取锁。如果blocking设置为0,如果无法获取锁,则线程立即返回0值,如果成功获取锁,则返回1。如果blocking设置为1,线程将阻塞并等待锁被释放。

Example

的中文翻译为:

示例

The release() method of the new lock object is used to release the lock when it is no longer required.

import threading
import time
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)
      # 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 = myThread(1, "Thread-1", 1)
thread2 = myThread(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: Mon Sep 19 08:57:59 2022
Thread-1: Mon Sep 19 08:58:00 2022
Thread-1: Mon Sep 19 08:58:01 2022
Thread-2: Mon Sep 19 08:58:03 2022
Thread-2: Mon Sep 19 08:58:05 2022
Thread-2: Mon Sep 19 08:58:07 2022
Exiting Main Thread