Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
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
Python Parallel Programming Cookbook

You're reading from   Python Parallel Programming Cookbook Master efficient parallel programming to build powerful applications using Python

Arrow left icon
Product type Paperback
Published in Aug 2015
Publisher
ISBN-13 9781785289583
Length 286 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Giancarlo Zaccone Giancarlo Zaccone
Author Profile Icon Giancarlo Zaccone
Giancarlo Zaccone
Arrow right icon
View More author details
Toc

Table of Contents (8) Chapters Close

Preface 1. Getting Started with Parallel Computing and Python 2. Thread-based Parallelism FREE CHAPTER 3. Process-based Parallelism 4. Asynchronous Programming 5. Distributed Python 6. GPU Programming with Python Index

Thread synchronization with RLock


If we want only the thread that acquires a lock to release it, we must use a RLock() object. Similar to the Lock() object, the RLock() object has two methods: acquire() and release(). RLock() is useful when you want to have a thread-safe access from outside the class and use the same methods from inside the class.

How to do it…

In the sample code, we introduced the Box class, which has the methods add() and remove(), respectively, that provide us access to the execute() method so that we can perform the action of adding or deleting an item, respectively. Access to the execute() method is regulated by RLock():

import threading
import time

class Box(object):
    lock = threading.RLock()
    def __init__(self):
        self.total_items = 0
    def execute(self,n):
        Box.lock.acquire()
        self.total_items += n
        Box.lock.release()
    def add(self):
        Box.lock.acquire()
        self.execute(1)
        Box.lock.release()
    def remove(self...
You have been reading a chapter from
Python Parallel Programming Cookbook
Published in: Aug 2015
Publisher:
ISBN-13: 9781785289583
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 $19.99/month. Cancel anytime
Banner background image