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

Start working with threads in Python

As mentioned briefly in the previous section, thread-based parallelism is the standard way of writing parallel programs. However, the Python interpreter is not fully thread-safe. In order to support multithreaded Python programs, a global lock called the Global Interpreter Lock (GIL) is used. This means that only one thread can execute the Python code at the same time; Python automatically switches to the next thread after a short period of time or when a thread does something that may take a while. The GIL is not enough to avoid problems in your own programs. Although, if multiple threads attempt to access the same data object, it may end up in an inconsistent state.

In this recipe, we simply show you how to create a single thread inside a Python program.

How to do it…

To execute this first example, we need the program helloPythonWithThreads.py:

## To use threads you need import Thread using the following code:
from threading import Thread

##Also we use the sleep function to make the thread "sleep" 
from time import sleep

## To create a thread in Python you'll want to make your class work as a thread.
## For this, you should subclass your class from the Thread class
class CookBook(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.message = "Hello Parallel Python CookBook!!\n"

##this method prints only the message 
    def print_message(self):
        print (self.message)

##The run method prints ten times the message 
    def run(self):
        print ("Thread Starting\n")
        x=0
        while (x < 10):
            self.print_message()
            sleep(2)
            x += 1
        print ("Thread Ended\n")


#start the main process
print ("Process Started")

# create an instance of the HelloWorld class
hello_Python = CookBook()

# print the message...starting the thread
hello_Python.start()

#end the main process
print ("Process Ended")

To run the example, open the calling_Process.py program with the Python IDE and then press the F5 button on the keyboard.

You will see the following output in the Python shell:

How to do it…

How it works…

While the main program has reached the end, the thread continues printing its message every two seconds. This example demonstrates what threads are—a subtask doing something in a parent process.

A key point to make when using threads is that you must always make sure that you never leave any thread running in the background. This is very bad programming and can cause you all sorts of pain when you work on bigger applications.

lock icon The rest of the chapter is locked
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