0

Basically I have a function which just gets X amount of (true) random numbers from pinging a web service online. However it is rather slow since it waits for one request to be finished before going to the next. How would I go about adding multithreading (or processes?) into it so multiple requests are being sent and printed at the same time. (The order of these is unimportant)

Does Python have the ability to do this? If so how?

Thank you

Johhny
  • 47
  • 5
  • Possible duplicate of [Dead simple example of using Multiprocessing Queue, Pool and Locking](https://stackoverflow.com/questions/20887555/dead-simple-example-of-using-multiprocessing-queue-pool-and-locking) – Bierbarbar Jul 02 '18 at 05:22

1 Answers1

1

Yes. This can be done in Python. gevents is my goto library for anything relating to MultiThreading or MultiProcessing in Python.

A simple example would be:

import gevent
from gevent import Greenlet

def foo(message, n):
    """
    Each thread will be passed the message, and n arguments
    in its initialization.
    """
    gevent.sleep(n)
    print(message)

# Initialize a new Greenlet instance running the named function
# foo
thread1 = Greenlet.spawn(foo, "Hello", 1)

# Wrapper for creating and runing a new Greenlet from the named
# function foo, with the passed arguments
thread2 = gevent.spawn(foo, "I live!", 2)

# Lambda expressions
thread3 = gevent.spawn(lambda x: (x+1), 2)

threads = [thread1, thread2, thread3]

# Block until all threads complete.
gevent.joinall(threads)
Pruthvi Kumar
  • 868
  • 1
  • 7
  • 15