centos

Python在CentOS上的多线程应用

小樊
39
2025-11-03 21:23:42
栏目: 编程语言

在CentOS上使用Python编写多线程应用程序,你可以使用Python的内置模块threading

首先,确保你已经安装了Python。CentOS 7默认安装了Python 2.7,但我们将使用Python 3。如果你还没有安装Python 3,可以通过以下命令安装:

sudo yum install python3

接下来,创建一个名为multithreaded_app.py的Python脚本,并添加以下代码:

import threading

def print_numbers():
    for i in range(1, 11):
        print(f"Number from thread {threading.current_thread().name}: {i}")

def print_letters():
    for letter in 'abcdefghij':
        print(f"Letter from thread {threading.current_thread().name}: {letter}")

if __name__ == "__main__":
    thread1 = threading.Thread(target=print_numbers, name="Thread-1")
    thread2 = threading.Thread(target=print_letters, name="Thread-2")

    thread1.start()
    thread2.start()

    thread1.join()
    thread2.join()

    print("Finished executing both threads.")

这个脚本定义了两个函数:print_numbersprint_letters。我们创建了两个线程,每个线程分别执行这两个函数。threading.Thread类的target参数接受一个函数作为参数,name参数为线程命名。

start()方法用于启动线程,join()方法用于等待线程完成。当所有线程完成后,脚本将打印"Finished executing both threads."。

要运行此脚本,请在终端中输入以下命令:

python3 multithreaded_app.py

你将看到两个线程交替打印数字和字母。

请注意,Python的全局解释器锁(GIL)可能会限制多线程的性能。如果你需要充分利用多核处理器,可以考虑使用multiprocessing模块。

0
看了该问题的人还看了