Skip to content

Instantly share code, notes, and snippets.

@Kvanrooyen
Created May 22, 2019 20:40
Show Gist options
  • Save Kvanrooyen/7222e56ead4d50bf2f08029e22d596da to your computer and use it in GitHub Desktop.
Save Kvanrooyen/7222e56ead4d50bf2f08029e22d596da to your computer and use it in GitHub Desktop.
Threading in Python
# 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