Discuss / Python / 交作业

交作业

Topic source
from multiprocessing import *
import os

def run():
    print("process %s" % os.getpid())

if __name__ == '__main__':
    print("process %s" % os.getpid())
    p = process(target=run)
    p.start()
    p.join()
    print("end")
from multiprocessing import *
import time

def write(q):
    for n in range(11):
        q.put(n)
        print("write to queue >>> %d" % n)
        time.sleep(1)

def read(q):
    while true:
        print("read from queue >>> %d" % q.get())

if __name__ == "__main__":
    q = queue()
    pw = process(target = write, args = (q,))
    pr = process(target = read, args = (q,))
    pw.start()
    pr.start()
    pw.join()

    pr.terminate()
from multiprocessing import *
import os

def f(x):
    return x*x

if __name__ == "__main__":
    with Pool(2) as pool:
        print(pool.map(f, range(os.cpu_count())))
        res = pool.apply_async(f, [10])
        print(res.get())
        pool.close()
        pool.join()
        print("end")

  • 1

Reply