Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set the default subtitles language in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please see our video player troubleshooting guide to resolve the issue.

A Single Thread

Give Feedback

In this lesson, you’ll see how a single-threaded application gets blocked, resulting in a poor user experience. If you download the sample code, you can get your own copy of thread.py:


Sample Code (.zip)

12.9 KB

To learn more, you can also check out the documentation.

00:00 All right, welcome back! In this lesson, we’re going to write some code and create a very simple program to demonstrate some of the potential issues we might come across when we only have one thread to work with.

00:13 I’m going to define a function called myfunc(). It’s very simple, it takes no parameters, it just prints 'hello' and it returns True. And then I’ll create an entry point, so if __name__ == '__main__': so when we invoke this program from the command line, we’re just going to call myfunc().

00:36 I’m saving this file as thread.py and then I’m going to hop into a terminal and execute the program.

00:45 As probably expected, it just prints hello and it brings us back to our shell prompt.

00:52 Now let’s do something that introduces a block. We’ll just use time.sleep() and we’ll sleep for 10 seconds. We’ll import time.

01:02 And we’ll be using time.sleep() throughout this course to represent one of those blocks—something in our program that takes some time, whether it’s waiting for a user to input something, or doing some heavy computational lifting that takes maybe minutes or hours.

01:19 We’re just going to use this simple time.sleep() function to represent something that prevents us from returning back to __main__ and finishing our program.

01:29 Now let’s execute this thread.py and it prints hello, and now we’re blocked. We don’t have a shell prompt, we can’t do anything in our terminal unless we wanted to kill this process, but we just have to wait for it to finish so it can return True back to __main__, and now we can type stuff again.

01:51 This is just a very simple example to demonstrate some of the issues you’re going to run into when you want to create more efficient programs but you’re not using multi-threading.

Become a Member to join the conversation.