首页 > 编程语言 > 详细

进程线程_开启

时间:2020-03-28 21:08:22      阅读:54      评论:0      收藏:0      [点我收藏+]

1.进程开启消耗资源大,时间慢,线程开启消耗资源小,时间快

#开启进程方式1 
from multiprocessing import Process
import time

def work(name):
    print("target %s is running" %name)
    time.sleep(2)
    print("target %s is done" %name)
if __name__=="__main__":
    p1=Process(target=work,args=("egon",))
    p2=Process(target=work,args=("alex",))
    p1.start()#向操作系统发送请求,开启进程
    p2.start()
    print("主进程")
‘‘‘
主进程
target egon is running
target alex is running
target alex is done
target egon is done
‘‘‘
#开启进程方式1 
from multiprocessing import Process
import time

def work(name):
    print("target %s is running" %name)
    time.sleep(2)
    print("target %s is done" %name)
if __name__=="__main__":
    p1=Process(target=work,args=("egon",))
    p2=Process(target=work,args=("alex",))
    p1.start()#向操作系统发送请求,开启进程
    p2.start()
    print("主进程")
‘‘‘
主进程
target egon is running
target alex is running
target alex is done
target egon is done
‘‘‘
#开启线程方式1
from threading import Thread
import time
def work(name):
    print("target %s is running" %name)
    time.sleep(2)
    print("target %s is done" %name)
if __name__=="__main__":
    t1=Thread(target=work,args=("egon",))
    t2=Thread(target=work,args=("alex",))
    t1.start()
    t2.start()
    print("")

‘‘‘
target egon is running
target alex is running

target alex is done
target egon is don
‘‘‘

#开启线程方式2
from threading import Thread
import time
class MyThread(Thread):
    def __init__(self,name):
        super().__init__()
        self.name=name
    def run(self):
        print("target %s is running" %self.name)
        time.sleep(2)
        print("target %s is done" %self.name)
if __name__=="__main__":
    t1=MyThread("egon")
    t2=MyThread("alex")
    t1.start()
    t2.start()
    print("")

‘‘‘
target egon is running
target alex is running

target alex is done
target egon is done
‘‘‘

 

进程线程_开启

原文:https://www.cnblogs.com/hapyygril/p/12589092.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!