How to activate multi-threading in Python?

In Python, you can use the threading module to start multiple threads. The specific steps are as follows:

  1. performing a threading service
  2. use the threading module
  3. Define a function as the task to be executed by the thread.
  4. String
  5. t = threading.Thread(target=function_name, args=argument_list)
  6. commence()
  7. Initiate the start() function.

Here is a simple example demonstrating how to start two threads to perform different tasks.

import threading
import time

# 定义线程1的任务
def task1():
    for i in range(5):
        print("Task 1 executing...")
        time.sleep(1)

# 定义线程2的任务
def task2():
    for i in range(5):
        print("Task 2 executing...")
        time.sleep(1)

# 创建线程对象
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)

# 启动线程
t1.start()
t2.start()

# 等待线程执行完毕
t1.join()
t2.join()

print("All tasks completed.")

In the above example, task1 and task2 define the tasks executed by thread1 and thread2, respectively. Two thread objects, t1 and t2, are created using the Thread class and passed the corresponding task functions. Finally, the start() method is called to begin the threads, which will run concurrently in the background. Lastly, the join() method is used to wait for the threads to finish execution, and then the message “All tasks completed.” is output.

bannerAds