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
Python Parallel Programming Cookbook
Python Parallel Programming Cookbook

Python Parallel Programming Cookbook: Master efficient parallel programming to build powerful applications using Python

eBook
$9.99 $43.99
Paperback
$54.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Python Parallel Programming Cookbook

Chapter 2. Thread-based Parallelism

In this chapter, we will cover the following recipes:

  • How to use the Python threading module
  • How to define a thread
  • How to determine the current thread
  • How to use a thread in a subclass
  • Thread synchronization with Lock and RLock
  • Thread synchronization with semaphores
  • Thread synchronization with a condition
  • Thread synchronization with an event
  • How to use the with statement
  • Thread communication using a queue
  • Evaluating the performance of multithread applications
  • The criticality of multithreaded programming

Introduction

Currently, the most widely used programming paradigm for the management of concurrence in software applications is based on multithreading. Generally, an application is made by a single process that is divided into multiple independent threads, which represent activities of different types that run parallel and compete with each other.

Although such a style of programming can lead to disadvantages of use and problems that need to be solved, modern applications with the mechanism of multithreading are still used quite widely.

Practically, all the existing operating systems support multithreading, and in almost all programming languages, there are mechanisms that you can use to implement concurrent applications through the use of threads.

Therefore, multithreaded programming is definitely a good choice to achieve concurrent applications. However, it is not the only choice available—there are several other alternatives, some of which, inter alia, perform better on the definition...

Using the Python threading module

Python manages a thread via the threading package that is provided by the Python standard library. This module provides some very interesting features that make the threading-based approach a whole lot easier; in fact, the threading module provides several synchronization mechanisms that are very simple to implement.

The major components of the threading module are:

  • The thread object
  • The Lock object
  • The RLock object
  • The semaphore object
  • The condition object
  • The event object

In the following recipes, we examine the features offered by the threading library with different application examples. For the examples that follow, we will refer to the Python distribution 3.3 (even though Python 2.7 could be used).

How to define a thread

The simplest way to use a thread is to instantiate it with a target function and then call the start() method to let it begin its work. The Python module threading has the Thread() method that is used to run processes and functions in a different thread:

class threading.Thread(group=None,
                       target=None,
                       name=None,
                       args=(),
                       kwargs={}) 

In the preceding code:

  • group: This is the value of group that should be None; this is reserved for future implementations
  • target: This is the function that is to be executed when you start a thread activity
  • name: This is the name of the thread; by default, a unique name of the form Thread-N is assigned to it
  • args: This is the tuple of arguments that are to be passed to a target
  • kwargs: This is the dictionary of keyword arguments that are to be used for the target function

It is useful to spawn a thread and pass arguments to it that tell it what work to...

How to determine the current thread

Using arguments to identify or name the thread is cumbersome and unnecessary. Each Thread instance has a name with a default value that can be changed as the thread is created. Naming threads is useful in server processes with multiple service threads that handle different operations.

How to do it…

To determine which thread is running, we create three target functions and import the time module to introduce a suspend execution of two seconds:

import threading
import time

def first_function():
    print (threading.currentThread().getName()+\
           str(' is Starting \n'))
    time.sleep(2)
    print (threading.currentThread().getName()+\
           str( ' is Exiting \n'))
    return

def second_function():
    print (threading.currentThread().getName()+\
           str(' is Starting \n'))
    time.sleep(2)
    print (threading.currentThread().getName()+\
           str( ' is Exiting \n'))
    return

def...

How to use a thread in a subclass

To implement a new thread using the threading module, you have to do the following:

  • Define a new subclass of the Thread class
  • Override the _init__(self [,args]) method to add additional arguments
  • Then, you need to override the run(self [,args]) method to implement what the thread should do when it is started

Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start() method, which will, in turn, call the run() method.

How to do it…

To implement a thread in a subclass, we define the myThread class. It has two methods that must be overridden with the thread's arguments:

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("Starting " +...

Thread synchronization with Lock and RLock

When two or more operations belonging to concurrent threads try to access the shared memory and at least one of them has the power to change the status of the data without a proper synchronization mechanism a race condition can occur and it can produce invalid code execution and bugs and unexpected behavior. The easiest way to get around the race conditions is the use of a lock. The operation of a lock is simple; when a thread wants to access a portion of shared memory, it must necessarily acquire a lock on that portion prior to using it. In addition to this, after completing its operation, the thread must release the lock that was previously obtained so that a portion of the shared memory is available for any other threads that want to use it. In this way, it is evident that the impossibility of incurring races is critical as the need of the lock for the thread requires that at a given instant, only a given thread can use this part of the shared...

Introduction


Currently, the most widely used programming paradigm for the management of concurrence in software applications is based on multithreading. Generally, an application is made by a single process that is divided into multiple independent threads, which represent activities of different types that run parallel and compete with each other.

Although such a style of programming can lead to disadvantages of use and problems that need to be solved, modern applications with the mechanism of multithreading are still used quite widely.

Practically, all the existing operating systems support multithreading, and in almost all programming languages, there are mechanisms that you can use to implement concurrent applications through the use of threads.

Therefore, multithreaded programming is definitely a good choice to achieve concurrent applications. However, it is not the only choice available—there are several other alternatives, some of which, inter alia, perform better on the definition of...

Using the Python threading module


Python manages a thread via the threading package that is provided by the Python standard library. This module provides some very interesting features that make the threading-based approach a whole lot easier; in fact, the threading module provides several synchronization mechanisms that are very simple to implement.

The major components of the threading module are:

  • The thread object

  • The Lock object

  • The RLock object

  • The semaphore object

  • The condition object

  • The event object

In the following recipes, we examine the features offered by the threading library with different application examples. For the examples that follow, we will refer to the Python distribution 3.3 (even though Python 2.7 could be used).

How to define a thread


The simplest way to use a thread is to instantiate it with a target function and then call the start() method to let it begin its work. The Python module threading has the Thread() method that is used to run processes and functions in a different thread:

class threading.Thread(group=None,
                       target=None,
                       name=None,
                       args=(),
                       kwargs={}) 

In the preceding code:

  • group: This is the value of group that should be None; this is reserved for future implementations

  • target: This is the function that is to be executed when you start a thread activity

  • name: This is the name of the thread; by default, a unique name of the form Thread-N is assigned to it

  • args: This is the tuple of arguments that are to be passed to a target

  • kwargs: This is the dictionary of keyword arguments that are to be used for the target function

It is useful to spawn a thread and pass arguments to it that tell it what work...

How to determine the current thread


Using arguments to identify or name the thread is cumbersome and unnecessary. Each Thread instance has a name with a default value that can be changed as the thread is created. Naming threads is useful in server processes with multiple service threads that handle different operations.

How to do it…

To determine which thread is running, we create three target functions and import the time module to introduce a suspend execution of two seconds:

import threading
import time

def first_function():
    print (threading.currentThread().getName()+\
           str(' is Starting \n'))
    time.sleep(2)
    print (threading.currentThread().getName()+\
           str( ' is Exiting \n'))
    return

def second_function():
    print (threading.currentThread().getName()+\
           str(' is Starting \n'))
    time.sleep(2)
    print (threading.currentThread().getName()+\
           str( ' is Exiting \n'))
    return

def third_function():
    print (threading.currentThread...

How to use a thread in a subclass


To implement a new thread using the threading module, you have to do the following:

  • Define a new subclass of the Thread class

  • Override the _init__(self [,args]) method to add additional arguments

  • Then, you need to override the run(self [,args]) method to implement what the thread should do when it is started

Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start() method, which will, in turn, call the run() method.

How to do it…

To implement a thread in a subclass, we define the myThread class. It has two methods that must be overridden with the thread's arguments:

import threading
import time

exitFlag = 0

class myThread (threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        print ("Starting " + self.name)
        print_time...

Thread synchronization with Lock and RLock


When two or more operations belonging to concurrent threads try to access the shared memory and at least one of them has the power to change the status of the data without a proper synchronization mechanism a race condition can occur and it can produce invalid code execution and bugs and unexpected behavior. The easiest way to get around the race conditions is the use of a lock. The operation of a lock is simple; when a thread wants to access a portion of shared memory, it must necessarily acquire a lock on that portion prior to using it. In addition to this, after completing its operation, the thread must release the lock that was previously obtained so that a portion of the shared memory is available for any other threads that want to use it. In this way, it is evident that the impossibility of incurring races is critical as the need of the lock for the thread requires that at a given instant, only a given thread can use this part of the shared...

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...
Left arrow icon Right arrow icon

Key benefits

  • 1. Design and implement efficient parallel software
  • 2. Master new programming techniques to address and solve complex programming problems
  • 3. Explore the world of parallel programming with this book, which is a go-to resource for different kinds of parallel computing tasks in Python, using examples and topics covered in great depth

Description

This book will teach you parallel programming techniques using examples in Python and will help you explore the many ways in which you can write code that allows more than one process to happen at once. Starting with introducing you to the world of parallel computing, it moves on to cover the fundamentals in Python. This is followed by exploring the thread-based parallelism model using the Python threading module by synchronizing threads and using locks, mutex, semaphores queues, GIL, and the thread pool. Next you will be taught about process-based parallelism where you will synchronize processes using message passing along with learning about the performance of MPI Python Modules. You will then go on to learn the asynchronous parallel programming model using the Python asyncio module along with handling exceptions. Moving on, you will discover distributed computing with Python, and learn how to install a broker, use Celery Python Module, and create a worker. You will understand anche Pycsp, the Scoop framework, and disk modules in Python. Further on, you will learnGPU programming withPython using the PyCUDA module along with evaluating performance limitations.

Who is this book for?

Python Parallel Programming Cookbook is intended for software developers who are well versed with Python and want to use parallel programming techniques to write powerful and efficient code. This book will help you master the basics and the advanced of parallel computing.

What you will learn

  • Synchronize multiple threads and processes to manage parallel tasks
  • Implement message passing communication between processes to build parallel applications
  • Program your own GPU cards to address complex problems
  • Manage computing entities to execute distributed computational tasks
  • Write efficient programs by adopting the event-driven programming model
  • Explore the cloud technology with DJango and Google App Engine
  • Apply parallel programming techniques that can lead to performance improvements

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 26, 2015
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781785289583
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Aug 26, 2015
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781785289583
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 158.97
Mastering Python High Performance
$48.99
Python Parallel Programming Cookbook
$54.99
Python 3 Object-Oriented Programming - Second Edition
$54.99
Total $ 158.97 Stars icon
Banner background image

Table of Contents

7 Chapters
1. Getting Started with Parallel Computing and Python Chevron down icon Chevron up icon
2. Thread-based Parallelism Chevron down icon Chevron up icon
3. Process-based Parallelism Chevron down icon Chevron up icon
4. Asynchronous Programming Chevron down icon Chevron up icon
5. Distributed Python Chevron down icon Chevron up icon
6. GPU Programming with Python Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.1
(11 Ratings)
5 star 63.6%
4 star 18.2%
3 star 0%
2 star 0%
1 star 18.2%
Filter icon Filter
Top Reviews

Filter reviews by




Jeff Dec 09, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I'm an intermediate coder, and this book is helping me to the next level with multiprocessing, testing and general strategies and tactics for attacking a challenge. Not for beginners, but a great asset after the intro books!!!
Amazon Verified review Amazon
Delio Dec 04, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is a complete overview of parallel programming and distributed systems. It includes the right amount of well explained theory and enough practical exercises. Although the book focuses on Python and some types of programming might not be supported by other languages, this book is very useful to whoever wants to have a clear understanding of all available kinds of parallel and distributed computing.
Amazon Verified review Amazon
ruben Oct 13, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
For all the users I did not have enough experience with this language, I could experience that with this book it helpsme a lot to understand the procedures and everything about this.With the recipes I could develop the main idea of a system, I really recommend this book. for all the user or developers that like to develop withslanguage.You will understand anche Pycsp, the Scoop framework, and disk modules in Python. Further on, you will learnGPU programming withPython using the PyCUDA module along with evaluating performance limitations.
Amazon Verified review Amazon
Natester Oct 12, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
For readers already familiar with the Python cookbooks from Packt, you'll know the recipes in the cookbooks strive to share practical examples without getting into esoteric details. The "Python Parallel Programming Cookbook" is more than a cookbook: It includes introductions to core concepts of programming architectures and programming architectures. These introductions are necessary to take advantage of parallel processing (not just with Python).Cookbook examples are also supported with discussion of other parallel processing concepts when relevant. This is definitely helpful in understanding the "why" some recipes are efficient. (Disclaimer: I've not tried all of the recipes in the book, but the descriptions with the examples I tried were helpful.)Also an important note about this book: It does not start with a quick intro to the basics of the Python language or how to configure a Python environment. This book is definitely for developers familiar with Python that need to take Python to the next level of performance--a good one to have in the collection.
Amazon Verified review Amazon
Kent P Pflibsen Nov 08, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very workable examples. Easy to follow and practice the principles.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.