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
.start()method. Never call.run()explicitly.__init__()methodYou don’t need to create a
Threadsubclass to use threads; a simple function will do:Output
btw, if
task()is CPU bound you could dofrom multiprocessing import Process as Threadto consume multiple cores (using multiple processes instead of threads).