• 技术文章 >常见问题 >Python常见问题

    Python如何生成线程

    silencementsilencement2019-09-12 13:57:06原创3950

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

    创建线程有3种方法:

    1、thread模块的start_new_thread函数

    2、继承自threading.Thread模块

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

    方法一、thread模块的start_new_thread函数

    其函数原型:

    1

    start_new_thread(function,atgs[,kwargs])

    其参数含义如下:

    1

    2

    3

    function: 在线程中执行的函数名

    args:元组形式的参数列表。

    kwargs: 可选参数,以字典的形式指定参数(即对一些参数进行指定初始化)

    代码

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    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方法

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    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方法

    1

    2

    3

    4

    5

    6

    7

    8

    9

    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的elif语句怎么用 下一篇:python request请求乱码怎么办

    相关文章推荐

    • Python中的线程和多线程是什么• Python中进程与线程的区别是什么• Python如何进行线程切换

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网