不管进程还是线程,主都会等着子结束而结束这是因为子进程/线程在执行的时候,会暂用一些资源,主就要收回这些资源
线程是系统调度的基本单位,进程是系统资源的基本单位
主线程会等待子线程结束才结束
import threading
import time
def sayHello():
print("------")
time.sleep(1)
for i in range(5):
t = threading.Thread(target=sayHello)
t.start()
print("*******")
Result:
------
------
------
------
------
******* #多个线程执行同一个函数,不会互相影响
#####################使用thread子类完成创建多线程###########
import threading
import time
class myThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
print(self.name+"num"+str(i)) #self.name保存的是当前的线程名字
if __name__ == "__main__":
t = myThread()
t.start() #MyThread没有start方法,为啥可以使用呢,这是threading.Thread中start去调用myThread的run方法
线程的执行顺序:
线程的执行顺序没有固定的,各个线程执行顺序不固定
线程共享全局变量:
线程全局变量是共用的,一个线程的更改其它线程使用也是更改的;而进程是相互独立的,一个进程修改不会对另一个进程产生影响
import time
import threading
g_num = 0
def work1():
global g_num
g_num += 1
print("work1, gum is %d"%g_num)
def work2():
global g_num
print("work2, gum is %d"%g_num)
t1 = threading.Thread(target = work1)
t1.start()
time.sleep(1)
t2 = threading.Thread(target = work2)
t2.start()
result:
work1, gum is 1
work2, gum is 1
列表作为参数传递也可以共享,变量不行需要global
import time
import threading
def work1(g_num):
g_num.append(4)
print("work1, guum is", g_num)
def work2(g_num):
time.sleep(1)
print("work2, guum is", g_num)
g_num = [1,2,3]
t1 = threading.Thread(target = work1, args=(g_num,))
t1.start()
t2 = threading.Thread(target = work2, args=(g_num,))
t2.start()
Result:
work1, guum is [1, 2, 3, 4]
work2, guum is [1, 2, 3, 4]