Поток с аргументами в Python: методы и примеры кода

Фраза «поток с args python» относится к концепции создания и выполнения потоков на языке программирования Python с аргументами. Ниже я представлю несколько способов достижения этой цели вместе с примерами кода.

Метод 1: использование модуля threading

import threading
def thread_function(name):
    print("Hello, " + name)
# Create a new thread and pass arguments
thread = threading.Thread(target=thread_function, args=("Alice",))
# Start the thread
thread.start()
# Wait for the thread to finish
thread.join()

Метод 2. Создание подкласса класса threading.Thread

import threading
class MyThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        print("Hello, " + self.name)
# Create a new instance of the custom thread class and pass arguments
thread = MyThread("Bob")
# Start the thread
thread.start()
# Wait for the thread to finish
thread.join()

Метод 3. Использование лямбда-функций

import threading
# Define a lambda function that takes arguments
thread_function = lambda name: print("Hello, " + name)
# Create a new thread and pass arguments
thread = threading.Thread(target=thread_function, args=("Charlie",))
# Start the thread
thread.start()
# Wait for the thread to finish
thread.join()

Метод 4: использование модуля concurrent.futures(Python 3+)

import concurrent.futures
def thread_function(name):
    print("Hello, " + name)
# Create a thread pool executor
with concurrent.futures.ThreadPoolExecutor() as executor:
    # Submit a task to the executor with arguments
    future = executor.submit(thread_function, "Dave")
    # Wait for the task to complete
    future.result()

Метод 5: использование модуля multiprocessing(для параллельного выполнения)

import multiprocessing
def process_function(name):
    print("Hello, " + name)
# Create a new process and pass arguments
process = multiprocessing.Process(target=process_function, args=("Eve",))
# Start the process
process.start()
# Wait for the process to finish
process.join()