Python Thread Safety - My First Tutorial for Real Python

Python Thread Safety - My First Tutorial for Real Python

My first tutorial for Real Python got published 🎉

"Python Thread Safety: Using a Lock and Other Techniques": https://realpython.com/python-thread-lock/

Why thread safety?

Below is a classic example of creating a singleton class is Python:

𝘤𝘭𝘢𝘴𝘴 𝘚𝘪𝘯𝘨𝘭𝘦𝘵𝘰𝘯𝘊𝘭𝘢𝘴𝘴(𝘰𝘣𝘫𝘦𝘤𝘵):

⠀𝘥𝘦𝘧 𝘯𝘦𝘸(𝘤𝘭𝘴):

⠀⠀𝘪𝘧 𝘯𝘰𝘵 𝘩𝘢𝘴𝘢𝘵𝘵𝘳(𝘤𝘭𝘴, '𝘪𝘯𝘴𝘵𝘢𝘯𝘤𝘦'):

⠀⠀⠀𝘤𝘭𝘴.𝘪𝘯𝘴𝘵𝘢𝘯𝘤𝘦 = 𝘴𝘶𝘱𝘦𝘳(𝘚𝘪𝘯𝘨𝘭𝘦𝘵𝘰𝘯𝘊𝘭𝘢𝘴𝘴, 𝘤𝘭𝘴).__𝘯𝘦𝘸__(𝘤𝘭𝘴)

⠀⠀𝘳𝘦𝘵𝘶𝘳𝘯 𝘤𝘭𝘴.𝘪𝘯𝘴𝘵𝘢𝘯𝘤𝘦

The SingletonClass is supposed to have only 1 object, but the code can lead to the creation of more than one instances when executed in a multithreaded environment.

Read the tutorial to spot such race conditions and learn to fix them using Python's synchronization primitives.

Read now at Real Python Website: https://realpython.com/python-thread-lock/


To view or add a comment, sign in

Explore content categories