콘텐츠로 건너뛰기

파이썬 스레드 값 반환하는 방법

[

Python Threads: Return Value

Introduction

In Python, threading is a powerful technique used to run multiple threads (also known as sub-threads) simultaneously within a single program. By using threading, we can improve program performance by executing tasks concurrently.

In this tutorial, we will explore how to obtain return values from threads in Python. We will provide detailed, step-by-step explanations and executable sample codes to help you understand the concept.

Prerequisites

Before we dive into the topic, make sure you have the following prerequisites:

  1. Basic understanding of Python syntax and functions.
  2. Python interpreter installed on your machine.

Creating a Simple Thread

Let’s start by creating a simple thread that prints a message. The return value of this thread will be None since it doesn’t perform any computation. Here’s the sample code:

import threading
def print_message():
print("Hello from the thread!")
thread = threading.Thread(target=print_message)
thread.start()
# Wait for the thread to finish execution
thread.join()
# Output: Hello from the thread!

In the above code, we first import the necessary threading module. Then we define a function print_message() which simply prints a message. Next, we create a Thread object and pass the print_message function as the target. The start() method is used to start the thread’s execution.

To obtain the return value from this thread, we use the join() method which waits for the thread to finish its execution. After the thread completes its task, it returns None.

Returning Values from Threads

To get the return value from a thread, we can make use of the return statement in the target function. Let’s see an example:

import threading
def calculate_sum(a, b):
return a + b
def main():
thread = threading.Thread(target=calculate_sum, args=(3, 4))
thread.start()
thread.join()
result = thread.result
print(f"The sum is: {result}")
if __name__ == "__main__":
main()
# Output: The sum is: 7

In the above code, we define a function calculate_sum(a, b) which takes two arguments and returns their sum. Inside the main() function, we create a thread by passing the calculate_sum function and its arguments to the Thread constructor. After starting the thread and waiting for its completion using join(), we can access the return value using thread.result.

Using Thread Subclass

Another approach to obtain the return value from a thread is by subclassing the Thread class and overriding its run() method. Here’s an example:

import threading
class SumThread(threading.Thread):
def __init__(self, a, b):
threading.Thread.__init__(self)
self.a = a
self.b = b
def run(self):
self.result = self.a + self.b
def main():
thread = SumThread(3, 4)
thread.start()
thread.join()
result = thread.result
print(f"The sum is: {result}")
if __name__ == "__main__":
main()
# Output: The sum is: 7

In the above code, we create a subclass SumThread that inherits from the Thread class. Inside the run() method, we calculate the sum of a and b and store it in the result attribute. By accessing this attribute after joining the thread, we can obtain the return value.

Conclusion

In this tutorial, we learned how to obtain return values from threads in Python. We covered the techniques of using the Thread class and subclassing it to achieve this. By using threads, we can execute multiple tasks concurrently, thereby improving the performance of our programs.

Remember, Python’s threading module provides powerful capabilities for parallel execution. Use this knowledge to optimize and enhance your Python programs.

Happy coding!