Multithreading in Python

in #utopian-io8 years ago (edited)

What will I Learn?

This tutorial covers the topics on Multithreading in Python.

Requirements

  • A PC/laptop with any Operating system such as Linux, Mac OSX, Windows OS
  • Preinstalled Python
  • Preinstalled Code Editors such as Atom, Sublime text or Pycharm IDE

Note: This tutorial is performed in Pycharm IDE in laptop with Ubuntu 17.1, 64 bit OS

Difficulty

Intermediate. I strongly recommend to learn all my previous tutorials before starting this. The link of previous tutorials are at the buttom of this tutorial.

Tutorial Content

Almost all programs that we run earlier in our previous tutorials has at least one thread. A thread is like a program which we executed sequentially earlier and
has a beginning, a body and an end. So, multithreading is the occurance of multiple threads in a program, in which each thread acts as single program and is different from each other
but uses same memory space unlike different programs. Because of sharing same space, threads can communicate more easily than separate programs.
Python has threading module to deal with multiple threads.

We will understand multithreading in Python by example.
At first, we will start our example by importing modules.

import threading
import time

time module in python gives different methods to use time related function. For example,

print(time.gmtime())

gives

time.struct_time(tm_year=2018, tm_mon=3, tm_mday=1, tm_hour=15, tm_min=8, tm_sec=21, tm_wday=3, tm_yday=60, tm_isdst=0)

For more details on time module, please visit here

Now let us create a function to calculate area of square. To learn more about functions please visit my previous tutorial Python tutorials for beginners : Part - III.

def area_sqr(length):
    for l in length:
        time.sleep(0.1)
        print('Area:',l*l)

here area_sqr function is created to calculate area of square which takes length as arguments. For every length we provide through a list it calculates the area.
time.sleep(0.1) delays the each iteration by 0.1 seconds. Execution process is stopped for 0.1 seconds before printing area of square. It is useful when we are doing multithreading.
Due to time.sleep() our CPU remains idle for the given time and could handle multple threads smoothly because multithreading will try to utilize it even if it's idle.
Also we define next function to calculate perimeter of square similar to that of area_sqr.

def peri_sqr(length):
    for l in length:
        time.sleep(0.1)
        print('Perimeter:',4 * l)

we provide list of length as

length=[4,5,6]

time.time() method of time module gives the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC) Thursday, 1 January 1970. We will record it to measure the time taken to finish this whole threading process after execution of the whole program.

t = time.time()

Now, to create a thread we will call threading.Thread method of threading module which takes target and args. target here passed is function name which we can think of as
task to be completed. It is called by the run() method of threading.Thread object and shows what activity is to be done in that particular thread. length is passed as args here, which is invoked
by target while creating thread.

thread1= threading.Thread(target=area_sqr, args=(length,))
thread2= threading.Thread(target=peri_sqr, args=(length,))

We will call start() to start thread. We should call start() equall to number of our threads.We call it once in that particular thread object.

thread1.start()
thread2.start()

join() makes ease to perform threading process by waiting them till they terminates.

thread1.join()
thread2.join()

Now we also print the time that took to finish up this whole process. We do that by subtracting the time we recorded before the process was started from the time recorded after
the process is finished.

print("Finished in : ",time.time()-t)

Our final code looks like:

import time
import threading


def area_sqr(length):
    for l in length:
        time.sleep(0.1)
        print('Area:', l * l)


def peri_sqr(length):
    for l in length:
        time.sleep(0.1)
        print('Perimeter:', 4 * l)


length = [ 4, 5, 6 ]

t = time.time()

thread1 = threading.Thread(target=area_sqr, args=(length,))
thread2 = threading.Thread(target=peri_sqr, args=(length,))

thread1.start()
thread2.start()

thread1.join()
thread2.join()

print("Finished in : ", time.time() - t)

Output:

Area: 16
Perimeter: 16
Perimeter: 20
Area: 25
Area: 36
Perimeter: 24
Finished in :  0.3012888431549072

Now let us run this program without using threads and see it's output.

import time


def area_sqr(length):
    for l in length:
        time.sleep(0.1)
        print('Area:', l * l)


def peri_sqr(length):
    for l in length:
        time.sleep(0.1)
        print('Perimeter:', 4 * l)


length = [ 4, 5, 6, 7 ]
t = time.time()

print(area_sqr(length))
print(peri_sqr(length))

print("Finished in : ", time.time() - t)

Output:

Area: 16
Area: 25
Area: 36
Area: 49
None
Perimeter: 16
Perimeter: 20
Perimeter: 24
Perimeter: 28
None
Finished in :  0.8018038272857666

*Comparing outputs of these programs, we can see that mutithreading process took 0.3012888431549072 secs to execute the program while without multithreads it took
0.8018038272857666 seconds which shows us that multithreading executes faster. We can see that in multiple threading process Area and Perimeter are printed alternately or one after another for each length passed but without
multithreading all Areas are printed first and then Perimeters are printed. This is due to that in multithreading two processes can be run in parallel.

all above codes including previous tutorials codes are available in my Github repo. Click here to download

For more details please visit Python Docs.

Curriculum

Python tutorials for beginners : Part - I

Python tutorials for beginners : Part - II

Python tutorials for beginners : Part - III

Object-oriented Python

Reading and writing to files in python

Matching and Searching Strings with regex in Python

Send mail with attachments in Python Program



Posted on Utopian.io - Rewarding Open Source Contributors

Sort:  

Thanks for the detail introduction. I think multiprocessing will do better work, as python has GIL lock to limit the multithreading.

Thank you for the contribution. It has been approved.

You can contact us on Discord.
[utopian-moderator]

Hey @programminghub I am @utopian-io. I have just upvoted you!

Achievements

  • You have less than 500 followers. Just gave you a gift to help you succeed!
  • Seems like you contribute quite often. AMAZING!

Suggestions

  • Contribute more often to get higher and higher rewards. I wish to see you often!
  • Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!

Get Noticed!

  • Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!

Community-Driven Witness!

I am the first and only Steem Community-Driven Witness. Participate on Discord. Lets GROW TOGETHER!

mooncryption-utopian-witness-gif

Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x

You got a 4.59% upvote from @buildawhale courtesy of @programminghub!
If you believe this post is spam or abuse, please report it to our Discord #abuse channel.

If you want to support our Curation Digest or our Spam & Abuse prevention efforts, please vote @themarkymark as witness.

You got a 52.17% upvote from @inciter courtesy of @programminghub!

Coin Marketplace

STEEM 0.04
TRX 0.33
JST 0.099
BTC 64522.52
ETH 1868.85
USDT 1.00
SBD 0.38