首页 > 代码库 > 线程,进程,协程

线程,进程,协程

一 线程

通过threading模块创建线程有两种方式,如下:

方式1:

#!/usr/bin/env python
# coding=utf-8

import threading

def f1(arg):
    print(arg)

if __name__ == __main__:
    t1 = threading.Thread(target=f1, args=(1,))
    t1.start()

# 输出
# 1

方法2:

class MyThread(threading.Thread):
    def __init__(self, func, args):
        self.func = func
        self.args = args
        super(MyThread, self).__init__()

    def run(self):
        self.func(self.args)

def f2(arg):
    print(arg)

obj = MyThread(f2, 123)
obj.start()

# 输出:
# 123

setDaemon方法

主线程不等子线程执行结束就推出

#!/usr/bin/env python
# coding=utf-8

import threading
import time

def f1(arg):
    time.sleep(2)
    print(start, arg)

if __name__ == __main__:

    t1 = threading.Thread(target=f1, args=(1,))
    t1.setDaemon(True) 
    t1.start()
    print(123)
# 输出:
# 123 而不是 1 12

join方法

表示主线程等待子线程执行完毕,join加参数表示最多等几秒

#!/usr/bin/env python
# coding=utf-8

import threading
import time

def f1(arg):
    time.sleep(2)
    print(start, arg)

if __name__ == __main__:

    t1 = threading.Thread(target=f1, args=(1,))
    t1.setDaemon(True) 
    t1.start()
    t1.join()
    print(123)
  # 输出:
  # 1 123

 

线程,进程,协程