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
0:01 of working with threads
0:03 starting and waiting for it to finish.
0:05 So of course, we're going to use the threading module.
0:08 This is built into CPython, you don't have to do anything.
0:11 There's no external dependencies.
0:12 It's just part of Python, that's great.
0:14 So then, we have some function
0:16 this is regular synchronous code that lives in here.
0:19 This is the code that's going to run on our other thread.
0:22 We're going to call this function
0:23 and then execute it somewhere else
0:25 and potentially wait on it.
0:27 So then we're going to create the thread
0:29 so create the thread object
0:30 set the target to the method name
0:32 the args to a tuple of arguments.
0:35 Notice above it takes a number, which is an integer
0:38 and an input, which is a list
0:40 so we're going to pass 20 and just an empty list.
0:43 And then we want to set the damon mode to be true.
0:46 That means if our main method exits for some reason
0:49 our process won't be become this zombie thing
0:52 that's still running
0:53 even though it appears to be exited, right?
0:55 It'll actually abort that, generate_data method
0:58 and just shut down the whole process
1:00 if our main thread exits.
1:02 Then we have to start it, right?
1:04 Creating the thread isn't enough to make it do anything.
1:06 You have to start it afterwards.
1:08 Potentially we can do other work now, theoretically right?
1:11 It's possible that the threads will be doing other stuff.
1:15 Again, remember the GIL, so its computational
1:18 then it doesn't help all that much, right?
1:21 But there are plenty of reasons where it will work
1:22 like talking to external systems, using networks
1:24 files and so on.
1:26 And then finally, were just going to wait for completion.
1:29 So instead of letting our program exit and abort the thread
1:31 we say work.join and we saw
1:33 that we can give it a time out if we like
1:35 but we don't have to.
1:37 Alright, so this is the overall basic API
1:39 of working with threads in python.