概述
在本文中,我们将看到两个没有多线程的 Python 代码示例,用于从摄像头读取视频帧。我们将看到使用/不使用多线程获得的 FPS 的差异。
什么是多线程?
线程是进程中的一个执行单元。多线程是指通过在线程之间快速切换对 CPU 的控制(称为上下文切换)来并发执行多个线程。在我们的示例中,我们将看到多线程通过提高 FPS(每秒帧数)实现更快的实时视频处理。
Python中的线程基础
以下代码片段显示了如何使用python 中的threading
模块创建线程:
# importing the threading module
import threading
# importing the time module
import time
# Function to print "Hello", however, the function sleeps
# for 2 seconds at the 11th iteration
def print_hello():
for i in range(20):
if i == 10:
time.sleep(2)
print("Hello")
# Function to print numbers till a given number
def print_numbers(num):
for i in range(num+1):
print(i)
# Creating the threads. Target is set to the name of the
# function that neeeds to be executed inside the thread and
# args are the arguments to be supplied to the function that
# needs to be executed.
print("Greetings from the main thread.")
thread1 = threading.Thread(target = print_hello, args = ())
thread2 = threading.Thread(target = print_numbers, args = (10,))
# Starting the two threads
thread1.start()
thread2.start()
print("It's the main thread again!")
让我们通过跟踪代码的执行来尝试理解输出:
主线程执行。打印“Greetings from the main thread”,创建
thread1
和thread2
并启动线程。发生上下文切换,开始执行
thread1
。在前十次迭代之后,
thread1
进入睡眠状态,thread2
开始执行,在下一次上下文切换之前完成。现在,主线程获得了 CPU 的控制权并打印出“It’s the main thread again!”
另一个上下文切换发生,
thread2
恢复执行并完成。