码迷,mamicode.com
首页 > 编程语言 > 详细

python3多进程和进程池

时间:2018-11-26 00:06:16      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:import   ==   独立   多进程   art   proc   分配   main   style   

#一个程序运行起来之后,代码+用到的资源称之为进程,它是操作系统分配资源的基本单位,不仅可以通过线程完成多任务,进程也是可以的
#进程之间是相互独立的
#cpu密集的时候适合用多进程
#多进程并发
import multiprocessing
from multiprocessing import Pool
import time
def test1():
    for i in range(10):
        time.sleep(1)
        print(test, i)

def test2():
    for i in range(10):
        time.sleep(1)
        print(test, i)

if __name__ == __main__:
    p1 = multiprocessing.Process(target=test1)
    p2 = multiprocessing.Process(target=test2)
    p1.start()
    p2.start()
#进程之间不共享
import multiprocessing
from multiprocessing import Pool
import time
import threading
g_num = 0
def edit():
    global g_num
    for i in range(10):
        g_num += 1

def reader():
    print(g_num)


if __name__ == __main__:
    # t1 = threading.Thread(target=edit)
    # t2 = threading.Thread(target=reader)
    # t1.start()
    # t2.start()
    p1 = multiprocessing.Process(target=edit)
    p2 = multiprocessing.Process(target=reader())
    p1.start()
    p1.join()
    p2.start()
#进程池实现并发
import multiprocessing
from multiprocessing import Pool
import time
import threading
g_num = 0
def test1():
    for i in range(10):
        time.sleep(1)
        print(test1, i)

def test2():
    for i in range(10):
        time.sleep(1)
        print(test2, i)


if __name__ == __main__:
    # t1 = threading.Thread(target=edit)
    # t2 = threading.Thread(target=reader)
    # t1.start()
    # t2.start()
    # p1 = multiprocessing.Process(target=edit)
    # p2 = multiprocessing.Process(target=reader())
    # p1.start()
    # p1.join()
    # p2.start()
    pool = Pool()
    pool.apply_async(test1)
    pool.apply_async(test2)
    pool.close()
    pool.join()

 

python3多进程和进程池

标签:import   ==   独立   多进程   art   proc   分配   main   style   

原文地址:https://www.cnblogs.com/fengzi7314/p/10017580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!