进程实例:
import threading
import time
def run(n):
print("task",n)
time.sleep(2)
t1 = threading.Thread(target=run,args = ("t1",))
t2 = threading.Thread(target=run,args = ("t2",))
t1.start()
t2.start()
多线程类实现方法:
class MyThread(threading.Thread):
def __init__(self,n):
super(MyThread,self).__init__()
self.n = n
def run(self):
print("runint task",self.n)
t1 = MyThread("t1")
t1.run()
一个程序有多个线程的话,子线程是并发执行的,怎么才能等等子线程结束结果呢,关健字join()
import threading
import time
def run(n):
print("task ",n )
time.sleep(2)
print("task done",n)
start_time = time.time()
t_objs = [] #存线程实例
for i in range(50):
t = threading.Thread(target=run,args=("t-%s" %i ,))
t.start()
t_objs.append(t) #为了不阻塞后面线程的启动,不在这里join,先放到一个列表里
# for t in t_objs: #循环线程实例列表,等待所有线程执行完毕
# t.join()
print("----------all threads has finished...")
print("cost:",time.time() - start_time)
# run("t1")
# run("t2")
如何做到主线程结束,子线程就结束呢,要用到守护线程 关健字 .setDaemon(True)
import threading
import time
def run(n):
print("task ",n )
time.sleep(2)
print("task done",n,threading.current_thread())
start_time = time.time()
t_objs = [] #存线程实例
for i in range(50):
t = threading.Thread(target=run,args=("t-%s" %i ,))
t.setDaemon(True) #把当前线程设置为守护线程
t.start()
t_objs.append(t) #为了不阻塞后面线程的启动,不在这里join,先放到一个列表里
# for t in t_objs: #循环线程实例列表,等待所有线程执行完毕
# t.join()
time.sleep(2)
print("----------all threads has finished...",threading.current_thread(),threading.active_count())
print("cost:",time.time() - start_time)
# run("t1")
# run("t2")
全局解析器锁
无论你的主机有多少个核,python的线程其实只有一个线程,一切都是假象 上下文切换。它是调用c写的原生内核接口,加锁方法,,,,python3.0以上会自动加锁,新版忽略
_author__ = "Alex Li"
import threading
import time
def run(n):
lock.acquire()
global num
num +=1
time.sleep(1)
lock.release()
lock = threading.Lock()
num = 0
t_objs = [] #线程实例
for i in range(50):
t = threading.Thread(target=run,args=("t-%s" %i ,))
t.start()
t_objs.append(t) #为了不阻塞后面线程的启动,不在这里join,先放到一个列表里
for t in t_objs: #循环线程实例列表,等待所有线程执行完毕
t.join()
print("----------all threads has finished...",threading.current_thread(),threading.active_count())
print("num:",num)
线程无法发挥计算机性能,,只适用io操作,大密集CPU操作时用进程 下面一人简单的例子创造进程
from
multiprocessing
import
Process
import
time
def
f(name):
time.sleep(
2
)
print
(
'hello'
, name)
if
__name__
=
=
'__main__'
:
p
=
Process(target
=
f, args
=
(
'bob'
,))
p.start()
p.join()
import multiprocessing
import time
def run(name):
time.sleep(1)
print('hello',name)
if __name__ == "__main__":
for i in range(10):
print("e")
p = multiprocessing.Process(target =run, args = ('xs',))
p.start()
p.join()
import multiprocessing
import time
def f(name):
time.sleep(1)
print('hello',name)
if __name__ == "__main__":
for i in range(10):
print("e")
p = multiprocessing.Process(target =f, args = ('xs',))
p.start()
p.join()
如何在进程中加入线程例子:
import multiprocessing
import time,threading
def thr():
print('输出当前线程',threading.get_ident())
def run(name):
time.sleep(1)
print('hello',name)
#没有参数直接忽略,逗号结束
t = threading.Thread(target=thr,)
t.start()
if __name__ == "__main__":
for i in range(10):
p = multiprocessing.Process(target =run, args = ('xs',))
p.start()
p.join()
#每一个进程都是父进程启动的,,,
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name',__name__)
print('父进程id',os.getppid())
print('自己的进程id',os.getpid())
def f(name):
info(' 33[31;1m dfdfdfdfdfdfd 33[0m')
print("hello",name)
if __name__=='__main__':
info(' 33[31;1m dfdfdfdfdfdfd 33[0m')
p = Process(target = f,args = ('bob',))
p.start()
p.join()
#每一个进程都是父进程启动的,,,
# 本程序的第一个父ID是pychrm 子进程是自己写的那个主函数,,而主函数调用手,子进程 变成了子进程的父进程 id
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name',__name__)
print('父进程id',os.getppid())
print('自己的进程id',os.getpid())
def f(name):
info(' 33[31;1m funcif 33[0m')
print("hello",name)
if __name__=='__main__':
info(' 33[31;1m pychrmfun 33[0m')
p = Process(target = f,args = ('bob',))
p.start()
p.join()