Python基础--多线程

来源:互联网 发布:软件架构 pdf 编辑:程序博客网 时间:2024/06/05 18:18

多线程在程序开发过程中特别重要,我们往往把一些耗时的操作在子线程中执行,这就是所谓的多线程了。

在C++11中,写了一些关于多线程的博客。

Python也不例外,当然也要有多线程了。

python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补

thread
通过start_new_thread函数来开启新的线程,位于thread模块中:
原型:

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

直接上代码:

import threadimport time# 为线程定义一个函数def print_time( threadName, delay):   count = 0   while count < 5:      time.sleep(delay)      count += 1      print "%s: %s" % ( threadName, time.ctime(time.time()) )# 创建两个线程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"while 1:   pass

threading
使用threading线程模块创建线程:

自定义一个类继承自threading.Thread

import threadingimport timeexitFlag = 0class myThread (threading.Thread):   #继承父类threading.Thread    def __init__(self, threadID, name, counter):        threading.Thread.__init__(self)        self.threadID = threadID        self.name = name        self.counter = counter    def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数         print "Starting " + self.name        print_time(self.name, self.counter, 5)        print "Exiting " + self.namedef print_time(threadName, delay, counter):    while counter:        if exitFlag:            thread.exit()        time.sleep(delay)        print "%s: %s" % (threadName, time.ctime(time.time()))        counter -= 1# 创建新线程thread1 = myThread(1, "Thread-1", 1)thread2 = myThread(2, "Thread-2", 2)# 开启线程thread1.start()thread2.start()print "Exiting Main Thread"

Thread.getName()

Thread.setName()

Thread.name

用于获取和设置线程的名称。

Thread.ident

获取线程的标识符。线程标识符是一个非零整数,只有在调用了start()方法之后该属性才有效,否则它只返回None。

Thread.is_alive()

Thread.isAlive()

判断线程是否是激活的(alive)。从调用start()方法启动线程,到run()方法执行完毕或遇到未处理异常而中断 这段时间内,线程是激活的。

Thread.join([timeout])
调用Thread.join将会使主调线程堵塞,直到被调用线程运行结束或超时。参数timeout是一个数值类型,表示超时时间,如果未提供该参数,那么主调线程将一直堵塞到被调线程结束

0 0