多线程的使用方法

Zss 发表于:

1.使用threading中的Thread模块,主线程会等待各个子线程全部执行完才结束

from threading import Thread
import time

#1. 如果多个线程执行的都是同一个函数的话,各自之间不会有影响,各是个的
def test():
    print("test")
    time.sleep(1)

for i in range(5):
    t = Thread(target=test)
    t.start()

2.与多进程类似,继承Thread后重写Thread的run方法,线程号为tid

import threading
import time

class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i) #name属性中保存的是当前线程的名字
            print(msg)

if __name__ == '__main__':
    t = MyThread()
    t.start()

3.线程的执行是根据系统调度的,执行时无序的

#coding=utf-8
import threading
import time

class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm "+self.name+' @ '+str(i)
            print(msg)
def test():
    for i in range(5):
        t = MyThread()
        t.start()
if __name__ == '__main__':
    test()

4.线程的全局变量为公用的,线程之间共享全局变量这是和进程之间的区别

from threading import Thread
import time

#线程之间共享全局变量
g_num = 100

def work1():
    global g_num
    for i in range(3):
        g_num += 1

    print("----in work1, g_num is %d---"%g_num)


def work2():
    global g_num
    print("----in work2, g_num is %d---"%g_num)


print("---线程创建之前g_num is %d---"%g_num)

t1 = Thread(target=work1)
t1.start()

#延时一会,保证t1线程中的事情做完
time.sleep(1)

t2 = Thread(target=work2)
t2.start()

5.当传递给函数的是列表,线程之间都是共享的,当线程1append一些元素给list后,线程2使用的list会得到改变