python 多进程+多线程——子进程开多线程

直接上代码:

import os
import time
from multiprocessing import Process, Lock
from threading import Thread, current_thread

n = 0


class AA:
    def __init__(self):
        self.mutex = Lock()

    def func_thread(self):
        while True:
            self.add1(1)

    def add1(self, id):
        global n
        self.mutex.acquire()
        mid = n
        time.sleep(1)
        n = mid + 1
        print("id", id, "   子线程:", current_thread().getName(), n, "   父进程: ", os.getpid())

        self.mutex.release()

    def func_thread2(self):
        while True:
            self.add1(2)


def func():
    obj = AA()
    global n
    n += 1
    print('子进程', n, os.getpid())
    obj.mutex.acquire()

    t = Thread(target=obj.func_thread, name="func_thread-1")
    t2 = Thread(target=obj.func_thread2, name="func_thread-2")
    t.start()
    t2.start()
    obj.mutex.release()


def foo():
    global n
    n += 1
    print('子进程', n, os.getpid())


if __name__ == '__main__':
    p1 = Process(target=foo)
    p2 = Process(target=func)
    p1.start()
    p2.start()
    print('主进程', n, os.getpid())

 

posted @ 2022-03-15 10:44  静静别跑  阅读(661)  评论(0编辑  收藏  举报