您的位置:首页 > 编程语言 > Python开发

python学习之路--multithreading

2017-10-22 21:44 369 查看
Starting a New Thread
To spawn anotherthread, you need to call following method available in thread module:

thread.start_new_thread(function,
args[, kwargs])

这种方法调用可以快速有效地在Linux和Windows中创建新的线程。
方法调用立即返回,子线程启动并使用传递的args列表调用函数。 当函数返回时,线程终止。
在这里,args是一个元组; 使用空的元组来调用函数而不传递任何参数。 kwargs是关键字参数的可选字典。
Example

#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName,
delay):
   count=0
  
while count
<5:
      time.sleep(delay)
      count+=1
     
print"%s: %s"%( threadName,
time.ctime(time.time()))
# Create two threads as follows
try:
   thread.start_new_thread( print_time,("Thread-1",2,))
   thread.start_new_thread( print_time,("Thread-2",4,))
except:
  
print"Error: unable to start thread"
while1:
  
pass
当执行上述代码时,会产生以下结果 –
Thread-1:ThuJan2215:42:172009
Thread-1:ThuJan2215:42:192009
Thread-2:ThuJan2215:42:192009
Thread-1:ThuJan2215:42:212009
Thread-2:ThuJan2215:42:232009
Thread-1:ThuJan2215:42:232009
Thread-1:ThuJan2215:42:252009
Thread-2:ThuJan2215:42:272009
Thread-2:ThuJan2215:42:312009
Thread-2:ThuJan2215:42:352009

虽然它对于低级线程非常有效,但与较新的线程模块(threading module)相比,线程模块非常有限。

The Threading Module:
Python 2.4中包含的较新的线程模块为线程提供了比上一节讨论的线程模块更强大的高级支持。
线程模块公开了线程模块的所有方法,并提供了一些其他方法:threading.activeCount(): Returns the number of thread objects that are active.
·       threading.currentThread(): Returns the number of thread objects in the caller's thread control.

·       threading.enumerate(): Returns a list of all thread objects that are currently active.

除了这些方法之外,线程模块还具有实现线程的Thread类。 Thread类提供的方法如下:
run(): The run() method is the entry point for a thread.
·       start(): The start()method starts a thread by calling the run method.

·       join([time]): The join()waits for threads to terminate.

·       isAlive(): TheisAlive() method checks whether a thread is still executing.

·       getName(): ThegetName() method returns the name of a thread.

·       setName(): ThesetName() method sets the name of a thread.

Creating Thread Using Threading Module
要使用线程模块实现新线程,您必须执行以下操作:
•定义Thread类的新子类。
•覆盖__init __(self [,args])方法以添加其他参数。
•然后,重写run(self [,args])方法来实现线程在启动时应该执行的操作。
一旦创建了新的Thread子类,就可以创建一个实例,然后通过调用start()来调用run()方法来启动一个新的线程。
Example

#!/usr/bin/python
import threading
import time
exitFlag=0
class myThread(threading.Thread):
  
def __init__(self, threadID,
name, counter):
      threading.Thread.__init__(self)
     
self.threadID= threadID
     
self.name= name
     
self.counter= counter
  
def run(self):
     
print"Starting "+self.name
      print_time(self.name,self.counter,5)
     
print"Exiting "+self.name
 
def print_time(threadName,
counter, delay):
  
while counter:
     
if exitFlag:
         threadName.exit()
      time.sleep(delay)
     
print"%s: %s"%(threadName,
time.ctime(time.time()))
      counter-=1
# Create new threads
thread1
= myThread(1,"Thread-1",1)
thread2
= myThread(2,"Thread-2",2)
# Start new Threads
thread1.start()
thread2.start()
print"ExitingMain Thread"
当执行上述代码时,会产生以下结果 –
StartingThread-1
StartingThread-2
ExitingMainThread
Thread-1:ThuMar2109:10:032013
Thread-1:ThuMar2109:10:042013
Thread-2:ThuMar2109:10:042013
Thread-1:ThuMar2109:10:052013
Thread-1:ThuMar2109:10:062013
Thread-2:ThuMar2109:10:062013
Thread-1:ThuMar2109:10:072013
ExitingThread-1
Thread-2:ThuMar2109:10:082013
Thread-2:ThuMar2109:10:102013
Thread-2:ThuMar2109:10:122013
ExitingThread-2

Synchronizing Threads
Python提供的线程模块包括一个简单易用的锁定机制,允许您同步线程。 通过调用Lock()方法创建一个新的锁,该方法返回新的锁。
新的锁定对象的获取(阻塞)方法用于强制线程同步运行。 可选的阻止参数使您能够控制线程是否等待获取锁定。
如果阻塞设置为0,如果无法获取锁定,则线程将立即返回0值,如果锁定已获取,则该线程返回1。 如果阻塞设置为1,则线程将阻塞并等待锁定被释放。
新的锁定对象的release()方法用于在不再需要锁定时释放该锁。Example

#!/usr/bin/python
import threading
import time
class myThread(threading.Thread):
  
def __init__(self, threadID,
name, counter):
      threading.Thread.__init__(self)
     
self.threadID= threadID
     
self.name= name
     
self.counter= counter
  
def run(self):
     
print"Starting "+self.name
     
# Get lock to synchronize threads
      threadLock.acquire()
      print_time(self.name,self.counter,3)
     
# Free lock to release next thread
      threadLock.release()
def print_time(threadName,
delay, counter):
  
while counter:
      time.sleep(delay)
     
print"%s: %s"%(threadName,
time.ctime(time.time()))
      counter-=1
threadLock= threading.Lock()
threads
=[]
# Create new threads
thread1
= myThread(1,"Thread-1",1)
thread2
= myThread(2,"Thread-2",2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for tin threads:
    t.join()
print"ExitingMain Thread"
当执行上述代码时,会产生以下结果 –
StartingThread-1
StartingThread-2
Thread-1:ThuMar2109:11:282013
Thread-1:ThuMar2109:11:292013
Thread-1:ThuMar2109:11:302013
Thread-2:ThuMar2109:11:322013
Thread-2:ThuMar2109:11:342013
Thread-2:ThuMar2109:11:362013
ExitingMainThread

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: