Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Working with Threads | Multithreading vs. Multiprocessing
Python Structural Programming

Working with Threads

メニューを表示するにはスワイプしてください

Python's threading module provides a simple yet powerful way to create and manage threads, enabling you to run multiple operations concurrently within a single process. Threads are lightweight units of execution that share the same memory space, making them suitable for tasks such as I/O operations, waiting for external resources, or updating user interfaces.

The lifecycle of a thread typically involves several stages:

  • Creation: a thread object is instantiated but not yet started;
  • Starting: the thread's start() method is called, moving it to the ready-to-run state;
  • Running: the thread executes its target function;
  • Termination: the thread finishes execution, either by completing its task or by encountering an unhandled exception.

Managing threads requires careful attention to synchronization, since threads share data and resources. Without proper synchronization, you may encounter race conditions or inconsistent state. The threading module offers primitives like Lock, RLock, and Event to help coordinate thread access to shared resources.

Here is a table presenting functions that will help you to create, manage, and synchronize threads effectively when working with concurrent tasks in Python.

The following example demonstrates how you can create and start multiple threads using the threading module, allowing several tasks to run concurrently.

123456789101112131415161718192021
import threading import time def print_numbers(name): for i in range(1, 4): print(f"Thread {name}: {i}") time.sleep(0.5) # Create thread objects thread1 = threading.Thread(target=print_numbers, args=("A",)) thread2 = threading.Thread(target=print_numbers, args=("B",)) # Start the threads thread1.start() thread2.start() # Wait for both threads to finish thread1.join() thread2.join() print("Both threads have finished.")

You define a function, print_numbers, that prints a sequence of numbers along with the thread name. When creating each thread, you pass arguments using the args parameter - here, each thread receives a different name ("A" or "B") so you can easily distinguish their outputs. By calling the start() method, both threads begin execution and run concurrently. The time.sleep(0.5) call inside the loop simulates a delay in execution, which allows the threads to interleave their outputs and makes it easy to see that both threads are running at the same time. The join() method is then used to wait for both threads to complete before moving on, ensuring that the main program does not finish prematurely. This approach allows tasks to run in parallel, making efficient use of waiting times and enabling concurrent execution within a single process.

question mark

Which of the following statements about thread synchronization in Python is correct?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt