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

python note 33 进程

时间:2019-07-20 17:01:15      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:python   BMI   start   ali   port   pool   继承方式   for   import   

1、进程

import multiprocessing
import threading

1、进程间的数据不共享

data_list = []

def task(arg):
    data_list.append(arg)
    print(data_list)


def run():
    for i in range(10):
        p = multiprocessing.Process(target=task,args=(i,))
        # p = threading.Thread(target=task,args=(i,))
        p.start()

if __name__ == __main__:
    run()

2、通过继承方式创建进程
class MyProcess(multiprocessing.Process):

    def run(self):
        print(当前进程,multiprocessing.current_process())


def run():
    p1 = MyProcess()
    p1.start()

    p2 = MyProcess()
    p2.start()

if __name__ == __main__:
    run()

2、进程数据共享

import multiprocessing
import threading
import queue
import time
进程间的数据共享:multiprocessing.Queue 
q = multiprocessing.Queue()

def task(arg,q):
    q.put(arg)

def run():
    for i in range(10):
        p = multiprocessing.Process(target=task, args=(i, q,))
        p.start()

    while True:
        v = q.get()
        print(v)
run()

 进程间的数据共享:Manager 

def task(arg,dic):
    time.sleep(2)
    dic[arg] = 100

if __name__ == __main__:
    m = multiprocessing.Manager()
    
    process_list = []
    for i in range(10):
        p = multiprocessing.Process(target=task, args=(i,dic,))
        p.start()

        process_list.append(p)

    while True:
        count = 0
        for p in process_list:
            if not p.is_alive():
                count += 1
        if count == len(process_list):
            break
    print(dic)

3、进程锁

import time
import threading
import multiprocessing

lock = multiprocessing.RLock()

def task(arg):
    print(鬼子来了)
    lock.acquire()
    time.sleep(2)
    print(arg)
    lock.release()

if __name__ == __main__:
    p1 = multiprocessing.Process(target=task,args=(1,))
    p1.start()

    p2 = multiprocessing.Process(target=task, args=(2,))
    p2.start()

4、进程池

import time
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

def task(arg):
    time.sleep(2)
    print(arg)

if __name__ == __main__:

    pool = ProcessPoolExecutor(5)
    for i in range(10):
        pool.submit(task,i)
import time
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

def task(arg):
    time.sleep(2)
    print(arg)

if __name__ == __main__:

    pool = ProcessPoolExecutor(5)
    for i in range(10):
        pool.submit(task,i)

 

python note 33 进程

标签:python   BMI   start   ali   port   pool   继承方式   for   import   

原文地址:https://www.cnblogs.com/P-Z-W/p/11218249.html

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