Multithreading : Lock objects - acquire() and release()
Python Multithread
Creating a thread and passing arguments to the threadIdentifying threads - naming and logging
Daemon thread & join() method
Active threads & enumerate() method
Subclassing & overriding run() and __init__() methods
Timer objects
Event objects - set() & wait() methods
Lock objects - acquire() & release() methods
RLock (Reentrant) objects - acquire() method
Using locks in the with statement - context manager
Condition objects with producer and consumer
Producer and Consumer with Queue
Semaphore objects & thread pool
Thread specific data - threading.local()
In this chapter, we'll learn how to control access to shared resources. The control is necessary to prevent corruption of data. In other words, to guard against simultaneous access to an object, we need to use a Lock object.
A primitive lock is a synchronization primitive that is not owned by a particular thread when locked. In Python, it is currently the lowest level synchronization primitive available, implemented directly by the _thread extension module.
- https://docs.python.org/3/library/threading.html.
A primitive lock is in one of two states, "locked" or "unlocked". It is created in the unlocked state. It has two basic methods, acquire() and release(). When the state is unlocked, acquire() changes the state to locked and returns immediately. When the state is locked, acquire() blocks until a call to release() in another thread changes it to unlocked, then the acquire() call resets it to locked and returns. The release() method should only be called in the locked state; it changes the state to unlocked and returns immediately. If an attempt is made to release an unlocked lock, a RuntimeError will be raised.
Here is our example code using the Lock object. In the code the worker() function increments a Counter instance, which manages a Lock to prevent two threads from changing its internal state at the same time.
import threading import time import logging import random logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',) class Counter(object): def __init__(self, start = 0): self.lock = threading.Lock() self.value = start def increment(self): logging.debug('Waiting for a lock') self.lock.acquire() try: logging.debug('Acquired a lock') self.value = self.value + 1 finally: logging.debug('Released a lock') self.lock.release() def worker(c): for i in range(2): r = random.random() logging.debug('Sleeping %0.02f', r) time.sleep(r) c.increment() logging.debug('Done') if __name__ == '__main__': counter = Counter() for i in range(2): t = threading.Thread(target=worker, args=(counter,)) t.start() logging.debug('Waiting for worker threads') main_thread = threading.currentThread() for t in threading.enumerate(): if t is not main_thread: t.join() logging.debug('Counter: %d', counter.value)
Output:
(Thread-1 ) Sleeping 0.04 (MainThread) Waiting for worker threads (Thread-2 ) Sleeping 0.11 (Thread-1 ) Waiting for a lock (Thread-1 ) Acquired a lock (Thread-1 ) Released a lock (Thread-1 ) Sleeping 0.30 (Thread-2 ) Waiting for a lock (Thread-2 ) Acquired a lock (Thread-2 ) Released a lock (Thread-2 ) Sleeping 0.27 (Thread-1 ) Waiting for a lock (Thread-1 ) Acquired a lock (Thread-1 ) Released a lock (Thread-1 ) Done (Thread-2 ) Waiting for a lock (Thread-2 ) Acquired a lock (Thread-2 ) Released a lock (Thread-2 ) Done (MainThread) Counter: 4
In this example, worker() tries to acquire the lock three separate times, and counts how many attempts it has to make to do so. In the mean time, locker() cycles between holding and releasing the lock, with short sleep in each state used to simulate load.
import threading import time import logging logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',) def locker(lock): logging.debug('Starting') while True: lock.acquire() try: logging.debug('Locking') time.sleep(1.0) finally: logging.debug('Not locking') lock.release() time.sleep(1.0) return def worker(lock): logging.debug('Starting') num_tries = 0 num_acquires = 0 while num_acquires < 3: time.sleep(0.5) logging.debug('Trying to acquire') acquired = lock.acquire(0) try: num_tries += 1 if acquired: logging.debug('Try #%d : Acquired', num_tries) num_acquires += 1 else: logging.debug('Try #%d : Not acquired', num_tries) finally: if acquired: lock.release() logging.debug('Done after %d tries', num_tries) if __name__ == '__main__': lock = threading.Lock() locker = threading.Thread(target=locker, args=(lock,), name='Locker') locker.setDaemon(True) locker.start() worker = threading.Thread(target=worker, args=(lock,), name='Worker') worker.start()
Output:
(Locker ) Starting (Locker ) Locking (Worker ) Starting (Worker ) Trying to acquire (Worker ) Try #1 : Not acquired (Locker ) Not locking (Worker ) Trying to acquire (Worker ) Try #2 : Acquired (Worker ) Trying to acquire (Worker ) Try #3 : Acquired (Locker ) Locking (Worker ) Trying to acquire (Worker ) Try #4 : Not acquired (Worker ) Trying to acquire (Worker ) Try #5 : Not acquired (Locker ) Not locking (Worker ) Trying to acquire (Worker ) Try #6 : Acquired (Worker ) Done after 6 tries
Python Multithread
Creating a thread and passing arguments to the threadIdentifying threads - naming and logging
Daemon thread & join() method
Active threads & enumerate() method
Subclassing & overriding run() and __init__() methods
Timer objects
Event objects - set() & wait() methods
Lock objects - acquire() & release() methods
RLock (Reentrant) objects - acquire() method
Using locks in the with statement - context manager
Condition objects with producer and consumer
Producer and Consumer with Queue
Semaphore objects & thread pool
Thread specific data - threading.local()
Python tutorial
Python Home
Introduction
Running Python Programs (os, sys, import)
Modules and IDLE (Import, Reload, exec)
Object Types - Numbers, Strings, and None
Strings - Escape Sequence, Raw String, and Slicing
Strings - Methods
Formatting Strings - expressions and method calls
Files and os.path
Traversing directories recursively
Subprocess Module
Regular Expressions with Python
Regular Expressions Cheat Sheet
Object Types - Lists
Object Types - Dictionaries and Tuples
Functions def, *args, **kargs
Functions lambda
Built-in Functions
map, filter, and reduce
Decorators
List Comprehension
Sets (union/intersection) and itertools - Jaccard coefficient and shingling to check plagiarism
Hashing (Hash tables and hashlib)
Dictionary Comprehension with zip
The yield keyword
Generator Functions and Expressions
generator.send() method
Iterators
Classes and Instances (__init__, __call__, etc.)
if__name__ == '__main__'
argparse
Exceptions
@static method vs class method
Private attributes and private methods
bits, bytes, bitstring, and constBitStream
json.dump(s) and json.load(s)
Python Object Serialization - pickle and json
Python Object Serialization - yaml and json
Priority queue and heap queue data structure
Graph data structure
Dijkstra's shortest path algorithm
Prim's spanning tree algorithm
Closure
Functional programming in Python
Remote running a local file using ssh
SQLite 3 - A. Connecting to DB, create/drop table, and insert data into a table
SQLite 3 - B. Selecting, updating and deleting data
MongoDB with PyMongo I - Installing MongoDB ...
Python HTTP Web Services - urllib, httplib2
Web scraping with Selenium for checking domain availability
REST API : Http Requests for Humans with Flask
Blog app with Tornado
Multithreading ...
Python Network Programming I - Basic Server / Client : A Basics
Python Network Programming I - Basic Server / Client : B File Transfer
Python Network Programming II - Chat Server / Client
Python Network Programming III - Echo Server using socketserver network framework
Python Network Programming IV - Asynchronous Request Handling : ThreadingMixIn and ForkingMixIn
Python Coding Questions I
Python Coding Questions II
Python Coding Questions III
Python Coding Questions IV
Python Coding Questions V
Python Coding Questions VI
Python Coding Questions VII
Python Coding Questions VIII
Python Coding Questions IX
Python Coding Questions X
Image processing with Python image library Pillow
Python and C++ with SIP
PyDev with Eclipse
Matplotlib
Redis with Python
NumPy array basics A
NumPy Matrix and Linear Algebra
Pandas with NumPy and Matplotlib
Celluar Automata
Batch gradient descent algorithm
Longest Common Substring Algorithm
Python Unit Test - TDD using unittest.TestCase class
Simple tool - Google page ranking by keywords
Google App Hello World
Google App webapp2 and WSGI
Uploading Google App Hello World
Python 2 vs Python 3
virtualenv and virtualenvwrapper
Uploading a big file to AWS S3 using boto module
Scheduled stopping and starting an AWS instance
Cloudera CDH5 - Scheduled stopping and starting services
Removing Cloud Files - Rackspace API with curl and subprocess
Checking if a process is running/hanging and stop/run a scheduled task on Windows
Apache Spark 1.3 with PySpark (Spark Python API) Shell
Apache Spark 1.2 Streaming
bottle 0.12.7 - Fast and simple WSGI-micro framework for small web-applications ...
Flask app with Apache WSGI on Ubuntu14/CentOS7 ...
Selenium WebDriver
Fabric - streamlining the use of SSH for application deployment
Ansible Quick Preview - Setting up web servers with Nginx, configure enviroments, and deploy an App
Neural Networks with backpropagation for XOR using one hidden layer
NLP - NLTK (Natural Language Toolkit) ...
RabbitMQ(Message broker server) and Celery(Task queue) ...
OpenCV3 and Matplotlib ...
Simple tool - Concatenating slides using FFmpeg ...
iPython - Signal Processing with NumPy
iPython and Jupyter - Install Jupyter, iPython Notebook, drawing with Matplotlib, and publishing it to Github
iPython and Jupyter Notebook with Embedded D3.js
Downloading YouTube videos using youtube-dl embedded with Python
Machine Learning : scikit-learn ...
Django 1.6/1.8 Web Framework ...
Ph.D. / Golden Gate Ave, San Francisco / Seoul National Univ / Carnegie Mellon / UC Berkeley / DevOps / Deep Learning / Visualization