Threads python return value

How to Return Values from a Thread

Summary: in this tutorial, you will learn how to return values from a child thread to the main thread by extending the threading.Thread class.

When a Python program starts, it has a single thread called the main thread. Sometimes, you want to offload I/O tasks to new threads and execute them concurrently. Additionally, you may also want to get the return values from these threads from the main thread.

To return a value from a thread, you can extend the Thread class and store that value in the instance of the class.

The following example illustrates how to check a specified URL and return its HTTP status code in a separate thread:

from threading import Thread import urllib.request class HttpRequestThread(Thread): def __init__(self, url: str) -> None: super().__init__() self.url = url self.http_status_code = None self.reason = None def run(self) -> None: try: response = urllib.request.urlopen(self.url) self.http_status_code = response.code except urllib.error.HTTPError as e: self.http_status_code = e.code except urllib.error.URLError as e: self.reason = e.reason def main() -> None: urls = [ 'https://httpstat.us/200', 'https://httpstat.us/400' ] # create new threads threads = [HttpRequestThread(url) for url in urls] # start the threads [t.start() for t in threads] # wait for the threads to complete [t.join() for t in threads] # display the URLs with HTTP status codes [print(f' : ') for t in threads] if __name__ == '__main__': main() def main() -> None: urls = [ 'https://httpstat.us/200', 'https://httpstat.us/400' ] # create new threads threads = [HttpRequestThread(url) for url in urls] # start the threads [t.start() for t in threads] # wait for the threads to complete [t.join() for t in threads] # display the URLs with HTTP status codes [print(f' : ') for t in threads] Code language: Python (python)
ttps://httpstat.us/200: 200 https://httpstat.us/400: 400Code language: Python (python)

First, define the HttpRequestThread class that extends the Thread class:

class HttpRequestThread(Thread): # . Code language: Python (python)

Second, define the __init__() method that accepts a URL. Inside the __init__() method adds url , http_status_code , and reason instance variables. The http_status_code will store the status code of the url at the time of checking and the reason will store the error message in case an error occurs:

def __init__(self, url: str) -> None: super().__init__() self.url = url self.http_status_code = None self.reason = NoneCode language: Python (python)

Third, override the run() method that uses the urllib library to get the HTTP status code of the specified URL and assigns it to http_status_code field. If an error occurs, it assigns the error message to the reason field:

def run(self) -> None: try: response = urllib.request.urlopen(self.url) self.http_status_code = response.code except urllib.error.HTTPError as e: self.http_status_code = e.code except urllib.error.URLError as e: self.reason = e.reasonCode language: Python (python)

Later, we can access the url , http_status_code , and reason from the instance of the HttpRequestThread class.

Fourth, define the main() function that creates instances of the HttpRequestThread class, start the threads, wait for them to complete, and get the result from the instances:

def main() -> None: urls = [ 'https://httpstat.us/200', 'https://httpstat.us/400' ] # create new threads threads = [HttpRequestThread(url) for url in urls] # start the threads [t.start() for t in threads] # wait for the threads to complete [t.join() for t in threads] # display the URLs with HTTP status codes [print(f' : ') for t in threads]Code language: Python (python)

Summary

  • Extend the Thread class and set the instance variables inside the subclass to return the values from a child thread to the main thread.

Источник

Get a Return Value From a Thread in Python

Get a Return Value From a Thread in Python

  1. HelloWorld Program Using Multi-Threading in Python
  2. Get a Return Value From a Function Running in Thread in Python

This article will first discuss thread basics and a code for starting a thread in Python. After this, we will discuss a code to get the value return from a function running in a thread.

A thread is a lightweight execution unit within a process with its own program execution states. A process runs multiple threads to achieve concurrency (and sometimes parallelism).

The main difference between a process and a thread is that each process has a separate disjoint address space, while multiple threads of the same process share the same address space of a single process. This means the threads can communicate using the shared memory without requiring additional pipes (Ordinary pipes or FIFOs) or any message passing interface.

HelloWorld Program Using Multi-Threading in Python

Consider the following code:

from threading import Thread  # A function for threads. def first_function():  print('Hello World')  print ("main program start")  thread_1 = Thread(target=first_function) thread_2 = Thread(target=first_function) thread_1.start() thread_2.start()  print ("main ends") 

In the above code, first, we used the from threading import Thread statement to import the Thread class to use the multi-threading. We defined a function first_function() which displays Hello World , and used the Thread() class to instantiate the threads.

We created two instances of the Thread() class by passing the first_function() as a target function to run. The target attribute specifies the function to be executed by the Thread() .

Once the Thread() instances are created, we can run and execute these threads using the .start() method.

Pass Arguments to a Function Running in Thread

Consider the following code:

from threading import Thread  def first_function(name, id):  print('Hello World from ', name, " id)  thread_1 = Thread(target=first_function, args=("Thread 1", 1)) thread_2 = Thread(target=first_function, args=("Thread 2", 2)) thread_1.start() thread_2.start() 

In the above code, we defined the function first_function(name, id) , receiving two arguments, name and id . We passed these arguments as a tuple using args in the Thread class.

We created two Thread class objects and passed the arguments args=(«Thread 1», 1) and args=(«Thread 2», 2) to thread_1 and thread_2 respectively. Further, thread_1.start() and thread_2.start() are used to run these threads.

Get a Return Value From a Function Running in Thread in Python

There are different ways to get a return value from a function running in a thread.

Pass a Mutable Object to the Function

We can get a value from a function running in a thread by passing a mutable object to the function; the function places the return value in that object. Consider the following code:

from threading import Thread  def first_function(first_argu, return_val):  print (first_argu)  return_val [0] = "Return Value from " + first_argu  return_val_from_1= [None]*1 return_val_from_2= [None]*1  thread_1 = Thread(target=first_function, args=("Thread 1", return_val_from_1)) thread_2 = Thread(target=first_function, args=("Thread 2", return_val_from_2))  thread_1.start() thread_2.start()  thread_1.join() thread_2.join()  print (return_val_from_1) print (return_val_from_2) 

The above code defined a function first_function which receives two arguments: first_argu and return_val . The first_function display the value of first_argu and place the return value in the 0 indexes of return_val .

We create thread using Thread class and pass two arguments including a list args=(«Thread 1», return_val_from_1) and args=(«Thread 2», return_val_from_2) for thread_1 and thread_2 respectively. return_val_from_1 and return_val_from_2 are used to get value from the function.

thread_1.join() and thread_2.join() are used to wait for the main program to complete both threads.

Let’s look into the output for the above code snippet:

Python Threading Return Value - Output 1

Use the join Method

The join method is another way to get a return value from a function running in a thread. Consider the following code:

from threading import Thread  def first_function(first_argu):  print (first_argu)  return "Return Value from " + first_argu  class NewThread(Thread):  def __init__(self, group=None, target=None, name=None,  args=(), kwargs=<>):  Thread.__init__(self, group, target, name, args, kwargs)  def run(self):  if self._target != None:  self._return = self._target(*self._args, **self._kwargs)  def join(self, *args):  Thread.join(self, *args)  return self._return  thread_1 = NewThread(target=first_function, args=("Thread 1", )) thread_2 = NewThread(target=first_function, args=("Thread 2", ))  thread_1.start() thread_2.start()  print (thread_1.join()) print (thread_2.join()) 

In the above code, we define a customized class, NewThread , a subclass of the Thread class. We redefine the run and join methods.

Once we create a thread and start, the return value from first_function is returned from the join() method.

The output of the following code is as follows:

Python Threading Return Value - Output 2

Related Article — Python Threading

Источник

Читайте также:  Проверить содержит ли ваша строка подстроку java используем метод string contains
Оцените статью