Learn Before
Code

Threading Example

Here is a simple example of using threads to print a string.

import threading def f(): print("Hello World!", threading.currentThread().getName()) if __name__ == '__main__': threads = [threading.Thread(target=f) for x in range(3) # Creates list of threads -> [Thread-1, Thread-2, Thread-3] for i in threads: i.start() for i in threads: i.join()

The .start() method signals the thread to begin execution. Alternatively, the .join() method signals for the thread to stop once it is done executing the function. The code above printed:

Hello World! Thread-1 Hello World! Thread-2 Hello World! Thread-3

0

1

Updated 2021-03-31

Tags

Python Programming Language

Data Science