Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is run() method synchronous in Python 3.2?

I am a newbie in Python. I have written following program and expecting all the threads to work in parallel while they are working sequentially. Can you please suggest where is the problem:

#! /usr/bin/env python3.2

# Import required libraries
import sys
import threading
import time

# Scan command line arguments
noOfThreads     = int( sys.argv[1] )

# Initialize an array for storing thread IDs
threadList = [ None ] * ( noOfThreads + 1 )

# Define a class Fast which implements threading
class Fast( threading.Thread ):
    def __init__( self, threadId ):
        self.threadID = threadId

    def run( self ):
        print( "P(" + str( self.threadID ) + ") sleeping" )
        time.sleep(5)
        print( "P(" + str( self.threadID ) + ") entering CS" )
        # CS
        print( "P(" + str( self.threadID ) + ") exiting CS" )

# Initiate and run the threads
for thrId in range( 1, noOfThreads + 1 ):
    threadList[ thrId ] = Fast( thrId )
    threadList[ thrId ].run()

O/P of the program when run with with 3 threads:

P(1) sleeping
P(1) entering CS
P(1) exiting CS
P(2) sleeping
P(2) entering CS
P(2) exiting CS
P(3) sleeping
P(3) entering CS
P(3) exiting CS
like image 548
Piyush Kansal Avatar asked Apr 21 '26 02:04

Piyush Kansal


1 Answers

  • to start a thread call its .start() method. Never call .run() explicitly
  • you forgot to call parent .__init__() method

You don't need to create a Thread subclass to use threads; a simple function will do:

#!/usr/bin/env python3
import sys
import time
from threading import Thread

def task(tid):
    print("P({}) sleeping".format(tid))
    time.sleep(5)
    print("P({}) entering CS".format(tid))
    # CS
    print("P({}) exiting CS".format(tid))

# Scan command line arguments
thread_count = int(sys.argv[1])

threads = [Thread(target=task, args=(tid,)) for tid in range(thread_count)]
for t in threads:
    t.daemon = True # die if the program exits
    t.start() # start the thread

# wait for completion
for t in threads: t.join()

Output

P(0) sleeping
P(1) sleeping
P(2) sleeping
P(2) entering CS
P(2) exiting CS
P(0) entering CS
P(0) exiting CS
P(1) entering CS
P(1) exiting CS

btw, if task() is CPU bound you could do from multiprocessing import Process as Thread to consume multiple cores (using multiple processes instead of threads).

like image 60
jfs Avatar answered Apr 22 '26 21:04

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!