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
₹799 ₹3276.99
Paperback
₹4096.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781785286728
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 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
₹4500 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 ₹400 each
Feature tick icon Exclusive print discounts
₹5000 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 ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 11,843.97
Mastering Python High Performance
₹3649.99
Python Parallel Programming Cookbook
₹4096.99
Python 3 Object-Oriented Programming - Second Edition
₹4096.99
Total 11,843.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.