Python 如何使用线程进行编程

Python 如何使用线程进行编程

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

Python3中有两个支持线程使用的模块−

  • _thread − 在Python 3中已弃用

  • Threading − 在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,则线程阻塞并等待锁被释放。

示例

当不再需要锁时,可以使用新锁对象的release()方法释放锁。

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

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程