Async Techniques and Examples in Python Transcripts
Chapter: Threads
Lecture: Concept: Thread API

Login or purchase this course to watch this video and the rest of the course contents.
0:00 Let's review the basic API of working with threads starting and waiting for it to finish. So of course, we're going to use the threading module.
0:09 This is built into CPython, you don't have to do anything. There's no external dependencies. It's just part of Python, that's great.
0:15 So then, we have some function this is regular synchronous code that lives in here. This is the code that's going to run on our other thread.
0:23 We're going to call this function and then execute it somewhere else and potentially wait on it. So then we're going to create the thread
0:30 so create the thread object set the target to the method name the args to a tuple of arguments. Notice above it takes a number, which is an integer
0:39 and an input, which is a list so we're going to pass 20 and just an empty list. And then we want to set the damon mode to be true.
0:47 That means if our main method exits for some reason our process won't be become this zombie thing that's still running
0:54 even though it appears to be exited, right? It'll actually abort that, generate_data method and just shut down the whole process
1:01 if our main thread exits. Then we have to start it, right? Creating the thread isn't enough to make it do anything. You have to start it afterwards.
1:09 Potentially we can do other work now, theoretically right? It's possible that the threads will be doing other stuff.
1:16 Again, remember the GIL, so its computational then it doesn't help all that much, right? But there are plenty of reasons where it will work
1:23 like talking to external systems, using networks files and so on. And then finally, were just going to wait for completion.
1:30 So instead of letting our program exit and abort the thread we say work.join and we saw that we can give it a time out if we like but we don't have to.
1:38 Alright, so this is the overall basic API of working with threads in Python.

Talk Python's Mastodon Michael Kennedy's Mastodon