Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learning Concurrency in Python

You're reading from   Learning Concurrency in Python Build highly efficient, robust, and concurrent applications

Arrow left icon
Product type Paperback
Published in Aug 2017
Publisher Packt
ISBN-13 9781787285378
Length 360 pages
Edition 1st Edition
Languages
Concepts
Arrow right icon
Author (1):
Arrow left icon
Elliot Forbes Elliot Forbes
Author Profile Icon Elliot Forbes
Elliot Forbes
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Speed It Up! FREE CHAPTER 2. Parallelize It 3. Life of a Thread 4. Synchronization between Threads 5. Communication between Threads 6. Debug and Benchmark 7. Executors and Pools 8. Multiprocessing 9. Event-Driven Programming 10. Reactive Programming 11. Using the GPU 12. Choosing a Solution

Handling threads in Python


In this section of the chapter, we'll take a look at how you can effectively create and manage multiple threads in Python programs.

Starting loads of threads

The first example we'll look at is how we can start numerous threads all at once. We can create multiple thread objects by using a for loop and then starting them within the same for loop. In the following example, we define a function that takes in an integer and which sleeps for a random amount of time, printing both when it is starting and ending.

We then create a for loop which loops up to 10, and create 10 distinct thread objects that have their target set to our executeThread function. It then starts the thread object we've just created, and then we print out the current active threads.

Example

Let's now look at an example:

import threading
import time
import random
def executeThread(i):
print("Thread {} started".format(i))
sleepTime = random.randint(1,10)
time.sleep(sleepTime)
print("Thread {} finished executing...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime