Python中生成线程的方法有哪些-创新互联

创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!

为德州等地区用户提供了全套网页设计制作服务,及德州网站建设行业解决方案。主营业务为成都网站设计、成都网站建设、德州网站设计,以传统方式定制建设网站,并提供域名空间备案等一条龙服务,秉承以专业、用心的态度为用户提供真诚的服务。我们深信只要达到每一位用户的要求,就会得到认可,从而选择与我们长期合作。这样,我们也可以走得更远!

小编给大家分享一下Python中生成线程的方法有哪些,希望大家阅读完这篇文章后大所收获,下面让我们一起去探讨吧!

Python中有两个线程模块,分别是thread和threading,threading是thread的升级版。threading的功能更强大。

创建线程有3种方法:

1、thread模块的start_new_thread函数

2、继承自threading.Thread模块

3、用theading.Thread直接返回一个thread对象,然后运行它的start方法

方法一、thread模块的start_new_thread函数

其函数原型:

start_new_thread(function,atgs[,kwargs])

其参数含义如下:

function: 在线程中执行的函数名
args:元组形式的参数列表。
kwargs: 可选参数,以字典的形式指定参数(即对一些参数进行指定初始化)

代码

import thread
 
def hello(id = 0, interval = 2):
    for i in filter(lambda x: x % interval == 0, range(10)):
        print "Thread id : %d, time is %d\n" % (id, i)
 
if __name__ == "__main__":
 
    #thread.start_new_thread(hello, (1,2))   这种调用形式也是可用的
    #thread.start_new_thread(hello, (2,4))
     
    thread.start_new_thread(hello, (), {"id": 1})
    thread.start_new_thread(hello, (), {"id": 2})

方法二:继承自threading.Thread模块

注意:必须重写run函数,而且想要运行应该调用start方法

import threading
 
class MyThread(threading.Thread):
 
    def __init__(self, id, interval):
        threading.Thread.__init__(self)
 
        self.id = id
        self.interval = interval
 
    def run(self):
        for x in filter(lambda x: x % self.interval == 0, range(10)):
            print "Thread id : %d   time is %d \n" % (self.id, x)
 
if __name__ == "__main__":
    t1 = MyThread(1, 2)
    t2 = MyThread(2, 4)
 
    t1.start()
    t2.start()
 
    t1.join()
    t2.join()

方法三:用theading.Thread直接返回一个thread对象,然后运行它的start方法

import threading
 
def hello(id, times):
    for i in range(times):
        print "hello %s time is %d\n" % (id , i)
 
if __name__ == "__main__":
    t = threading.Thread(target=hello, args=("hawk", 5))
    t.start()

看完了这篇文章,相信你对Python中生成线程的方法有哪些有了一定的了解,想了解更多相关知识,欢迎关注创新互联-成都网站建设公司行业资讯频道,感谢各位的阅读!

当前题目:Python中生成线程的方法有哪些-创新互联
本文网址:https://www.cdcxhl.com/article12/copedc.html

成都网站建设公司_创新互联,为您提供做网站网站策划建站公司面包屑导航微信小程序品牌网站制作

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

营销型网站建设