Video I used to learn: https://www.youtube.com/watch?v=A_Z1lgZLSNc

Threading: Running pieces of code concurrently/at the same time

Python has something like this; it allows the coder to run two or maybe more pieces of code at the same time. Obviously, such a thing isn’t technically possible, but with how fast machines work it is very close to it. It takes turns running each part of a task, to give the illusion of them running at the same time.

Example code, from the video:

import threading
import time

done = False

def worker():
    counter = 0
    while not done:
        time.sleep(1)
        counter += 1
        print(counter)

worker()

This is our first function, and what it does is while ‘done’ is not set to True, it will slowly count up from 1 and so on, having a second between with the time.sleep function.

import threading
import time

done = False

def worker():
    counter = 0
    while not done:
        time.sleep(1)
        counter += 1
        print(counter)

worker()

input("Press enter to quit")
done = True

If the user puts anything in, it will set ‘done’ to True. However, we cannot reach that point, as the loop we have set up will go on indefinitely, so it cannot reach the input option. This exact problem, is where threading comes in.

import threading
import time

done = False

def worker():
    counter = 0
    while not done:
        time.sleep(1)
        counter += 1
        print(counter)

threading.Thread(target=worker).start()

input("Press enter to quit")
done = True

With this, it is now running our worker function, but it is also going past it. In a sense, it is ‘running it at the same time’ as the rest of our code.

((stopping here because… All this other stuff is way too much to take in and put into words. I get it, but it’s too overwhelming to try and voice what it means by myself.))

One response to “Jan 17, async”

  1. Mr. Wilmoth Avatar
    Mr. Wilmoth

    I love your post! You clearly spent some time on your reflection was excellent!

Leave a Reply

Your email address will not be published. Required fields are marked *