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

Standard data structures


Some of Python's traditional data structure features provide various degrees of thread safety by default. However, in most cases, we will have to define some form of a locking mechanism for controlling access to these data structures in order to guarantee thread safety.

Sets

During my time working with communication between multiple threads in Python, I discovered that one excellent solution to using sets in a thread-safe manner is to actually extend the set class, and to implement my own locking mechanism around the actions that I wish to perform.

Extending the class

If you are used to working in Python then extending the class should be a somewhat simple operation. We define a LockedSet class object, which inherits from our traditional Python set class. Within the constructor for this class, we create a lock object, which we'll use in subsequent functions in order to allow for thread-safe interactions.

Below our constructor, we define the add, remove, and contains functions...

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