侧边栏壁纸
  • 累计撰写 92 篇文章
  • 累计创建 35 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

python多线程与多进程

天明
2023-10-26 / 0 评论 / 0 点赞 / 35 阅读 / 1757 字 / 正在检测是否收录...

多线程与多进程

import threading, multiprocessing
from multiprocessing import Pool
import os, time, random

def loop(i):
    x = 0
    while True:
        x = x ^ 1

def test_threads():
    count_cpu=multiprocessing.cpu_count()
    for i in range(4):
        t = threading.Thread(target=loop)
        t.start()
def test_multiprocess():
    p = Pool(2)
    for i in range(2):
        p.apply_async(loop, args=(i,))
    print('Waiting for all subprocesses done...')
    p.close()
    p.join()

if __name__=='__main__':
    ##虽然是多线程,但是还是在1个cpu上
    test_threads()
    ##通过多进程实现多核任务
    test_multiprocess()
0

评论区