黑松山资源网 Design By www.paidiu.com

在Python中我们主要是通过thread和threading这两个模块来实现的,其中Python的threading模块是对thread做了一些包装的,可以更加方便的被使用,所以我们使用threading模块实现多线程编程。一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里。

将函数传递进Thread对象
复制代码 代码如下:
''' 
Created on 2012-9-5 
 
@author:  walfred
@module: thread.ThreadTest1 
@description:
'''   
import threading 
 
def thread_fun(num): 
    for n in range(0, int(num)): 
        print " I come from %s, num: %s" %( threading.currentThread().getName(), n) 
 
def main(thread_num): 
    thread_list = list(); 
    # 先创建线程对象 
    for i in range(0, thread_num): 
        thread_name = "thread_%s" %i 
        thread_list.append(threading.Thread(target = thread_fun, name = thread_name, args = (20,))) 
 
    # 启动所有线程    
    for thread in thread_list: 
        thread.start() 
 
    # 主线程中等待所有子线程退出 
    for thread in thread_list: 
        thread.join() 
 
if __name__ == "__main__": 
    main(3)

程序启动了3个线程,并且打印了每一个线程的线程名字,这个比较简单吧,处理重复任务就派出用场了,下面介绍使用继承threading的方式;

继承自threading.Thread类
复制代码 代码如下:
'''
Created on 2012-9-6
 
@author: walfred
@module: thread.ThreadTest2
''' 
 
import threading 
 
class MyThread(threading.Thread): 
    def __init__(self): 
        threading.Thread.__init__(self); 
 
    def run(self): 
        print "I am %s" %self.name 
 
if __name__ == "__main__": 
    for thread in range(0, 5): 
        t = MyThread() 
        t.start()

接下来的文章,将会介绍如何控制这些线程,包括子线程的退出,子线程是否存活及将子线程设置为守护线程(Daemon)。

黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com

P70系列延期,华为新旗舰将在下月发布

3月20日消息,近期博主@数码闲聊站 透露,原定三月份发布的华为新旗舰P70系列延期发布,预计4月份上市。

而博主@定焦数码 爆料,华为的P70系列在定位上已经超过了Mate60,成为了重要的旗舰系列之一。它肩负着重返影像领域顶尖的使命。那么这次P70会带来哪些令人惊艳的创新呢?

根据目前爆料的消息来看,华为P70系列将推出三个版本,其中P70和P70 Pro采用了三角形的摄像头模组设计,而P70 Art则采用了与上一代P60 Art相似的不规则形状设计。这样的外观是否好看见仁见智,但辨识度绝对拉满。