06月07, 2017

python多线程与多进程

多线程与多进程

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()

本文链接:https://blog.jnliok.com/post/python-thread-process.html

-- EOF --

Comments