python-multiprocessing模块

由于GIL的存在,python中的多线程其实并不是真正的多线程,如果想要充分使用多核CPU的资源,在python中大部分情况使用多进程。

from multiprocessing import Process
import time


def f(name):
    time.sleep(1)
    print('hello', name,time.ctime())

if __name__ == '__main__':
    p_list=[]
    for i in range(3):

        p = Process(target=f, args=('alvin',))
        p_list.append(p)
        p.start()

    for i in p_list:
        i.join()
    print('end')


from multiprocessing import Process
import time

class MyProcess(Process):

    # def __init__(self):
    #     super(MyProcess, self).__init__()
    #     #self.name = name

    def run(self):
        time.sleep(1)
        print ('hello', self.name,time.ctime())


if __name__ == '__main__':
    p_list=[]


    for i in range(3):
        p = MyProcess()
        p.daemon=True
        p.start()
        p_list.append(p)

    # for p in p_list:
    #     p.join()

    print('end')

猜你喜欢

转载自www.cnblogs.com/benchdog/p/9181113.html
今日推荐