To create a thread using the threading module:
The threading module has the thread class implementation threading. The thread class provides the following methods:
Run (): The entry point of the thread
Start (): Call the Run method to start the thread
Join (time): Waiting for thread to end
IsAlive (): Checks if a thread is still executing
GetName (): Returns the name of the thread
SetName (): Sets a name for a thread
To implement a new thread using the threading module, you need to do this first:
Defines a subclass of the thread class.
Overriding the __init__ (Self,[,args]) method to add additional parameters
Then, rewrite the run (Self[,args]) method to implement what you want to do after the thread starts
After you create a new thread subclass, you can create an instance of it and then reference start () to open a new thread, which in turn invokes the call method.
1. General Thread:
Example:
#!/usr/bin/python ImportThreadingImportTime exitflag=0classMyThread (Threading. Thread):def __init__(self, ThreadID, name, counter): Threading. Thread.__init__(self) self.threadid=ThreadID Self.name=name Self.counter=counterdefRun (self):Print "starting"+self.name print_time (Self.name, Self.counter,5) Print "Exiting"+Self.namedefprint_time (threadname, Delay, counter): whileCounter:ifexitFlag:thread.exit () time.sleep (delay)Print "%s:%s"%(ThreadName, Time.ctime (Time.time ())) counter-= 1#Create New ThreadsThread1 = MyThread (1,"Thread-1", 1) Thread2= MyThread (2,"Thread-2", 2) #Start New ThreadsThread1.start () Thread2.start ( )Print "Exiting Main Thread"
2. Synchronize Threads:
The threading module provided by Python includes an easy-to-implement locking mechanism that allows you to synchronize threads. Creates a new lock by calling the lock () implementation, which also returns this new lock.
The Accquire (blocking) method of the new lock object that forces the thread to run synchronously. The optional blocking parameter allows you to control whether a thread requests a lock.
If blocking is set to 0, the thread returns a value of 0 immediately when the lock cannot be acquired, while blocking is set to 1 o'clock, and the thread acquires the lock after the 1 value is returned. If blocking is set to 1, the thread will block until the lock is released.
The release () method of the new lock object is used to release locks that are no longer needed.
Example:
#!/usr/bin/python ImportThreadingImport TimeclassMyThread (Threading. Thread):def __init__(self, ThreadID, name, counter): Threading. Thread.__init__(self) self.threadid=ThreadID Self.name=name Self.counter=counterdefRun (self):Print "starting"+Self.name#Get Lock to synchronize threadsThreadlock.acquire () print_time (Self.name, Self.counter,3) #Free lock to release next threadthreadlock.release ()defprint_time (threadname, Delay, counter): whileCounter:time.sleep (Delay)Print "%s:%s"%(ThreadName, Time.ctime (Time.time ())) counter-= 1Threadlock=Threading. Lock () Threads= [] #Create New ThreadsThread1 = MyThread (1,"Thread-1", 1) Thread2= MyThread (2,"Thread-2", 2) #Start New ThreadsThread1.start () Thread2.start ( )#ADD threads to Thread listthreads.append (thread1) threads.append (thread2)#Wait for all threads to complete forTinchThreads:t.join ()Print "Exiting Main Thread"
3. Multi-threaded Priority queue:
The queue module allows you to create a new queue object to hold a certain number of items.
There are several ways to control the queue:
Get (): Removes an item from the queue and returns it
Put (): Put the item in the queue
Qsize (): Returns the number of items in the current queue
Empty (): Returns True if the queue is empty, or false instead
Full (): Returns True if the queue is filled, and vice versa false
Example:
#!/usr/bin/python ImportQueueImportThreadingImportTime exitflag=0classMyThread (Threading. Thread):def __init__(self, ThreadID, name, Q): Threading. Thread.__init__(self) self.threadid=ThreadID Self.name=name Self.q=QdefRun (self):Print "starting"+self.name process_data (self.name, SELF.Q)Print "Exiting"+Self.namedefProcess_data (ThreadName, q): while notExitFlag:queueLock.acquire ()if notworkqueue.empty (): Data=Q.get () queuelock.release ( )Print "%s Processing%s"%(threadname, data)Else: Queuelock.release () time.sleep (1) Threadlist= ["Thread-1","Thread-2","Thread-3"] NameList= [" One"," Both","three"," Four","Five"] Queuelock=Threading. Lock () WorkQueue= Queue.queue (10) Threads=[] ThreadID= 1#Create New Threads forTnameinchThreadlist:thread=MyThread (ThreadID, Tname, WorkQueue) Thread.Start () threads.append (thread) ThreadID+ = 1#Fill the queueQueuelock.acquire () forWordinchnameList:workQueue.put (Word) queuelock.release ()#Wait for the queue to empty while notworkqueue.empty ():Pass #Notify Threads It ' s time to exitExitflag = 1#Wait for all threads to complete forTinchThreads:t.join ()Print "Exiting Main Thread"
Python Learning-Multi-threading