Created
May 22, 2019 20:40
-
-
Save Kvanrooyen/7222e56ead4d50bf2f08029e22d596da to your computer and use it in GitHub Desktop.
Threading in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Testing of how threading works | |
# https://www.youtube.com/watch?v=ecKWiaHCEKs | |
""" | |
Threading: | |
- A new thread is spawned within the existing process | |
- Starting a thread is faster than starting a process | |
- Memory is shared between all threads | |
- Mutexes often necessary to control access to shared data | |
- One GIL (Global Interpreter Lock) for all threads | |
""" | |
from threading import Thread | |
import os | |
import math | |
def calc(num): | |
for i in range(0, 7000000): | |
math.sqrt(i) | |
def main(): | |
threads = [] | |
for i in range(os.cpu_count()): | |
print('Thread: %d' % i) | |
threads.append(Thread(target=calc, args=(40456654,))) | |
for thread in threads: | |
thread.start() | |
for thread in threads: | |
thread.join() | |
print('\n\nDone!') | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment