Friday, September 11, 2015

python: multithreading (3)


Abstract: the module of multiprocessing

The function Pool() from the module multiprocessing is used here.


The script:
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 11 11:15:46 2015

@author: yuan
"""
import itertools
import multiprocessing as mp
import time

#
def loop(tid,x=5):
    print 'ID:%s, input:%s\n' % (tid,x)
    while x==1000:
        x+=1
        time.sleep(1000)

#endless loop
def eloop(tid,x=5):
    print 'ID:%s, input:%s\n' % (tid,x)
    time.sleep(1)
    while True:
        x=x^1
       
#multi-threading
def multithreading():
    pool=mp.Pool(2)
    #pass one argument at a time
    pool.map(loop, range(5)) 
    #pass two arguments at a time
    pool.map(loop, itertools.izip(range(5), range(5))) 
    pool.close()
    pool.join()     


if __name__=="__main__":
    multithreading()
    print 'ok'

No comments:

Post a Comment