python_ thread write operation <1>

Thread read and write operations

import threading,random,queue
q = queue.Queue()
alist=[]
def shengchan():
    for i in range(10):
        alist.append(random.randint(1,20))
    q.put(alist)
    print('随机生成的十个数是%s'%alist)
def xiaofei():
    with open('xiabo.txt','w+',encoding='utf8') as f:
        f.write(str(q.get()))
        f.seek(0)
        c =f.read()
        print(c)
if __name__=='__main__':
    t1 = threading.Thread(target=shengchan)
    t2 = threading.Thread(target=xiaofei)
    t1.start()
    t2.start()

Pool related processes

from multiprocessing Import Pool   # import modules process pool 
Import OS, Time, Random   # introduction windows system, the time, the random number block 


# Print (random.random ()) 
DEF Task (name):   # name is a parameter, the first analytical function function 
    Print ( ' tasks running in S% (% D) ... ' % (name, os.getpid ()))   # print process pool pass parameters i, as well as process number 
    Start the time.time = ()   # a recording start time of 
    the time.sleep (random.random () *. 3)   # number randomly between 0-3 
    # Print (random.random () *. 3) integer% S% d% f string float 
    end time.time = ()   # end time of 
    print( ' Task% s% 0.2f run time ' % (name, (End - Start)))   # end can be obtained by subtracting the start time to calculate how long it ran a function of time 


IF  __name__ == ' __main__ ' :
     Print ( ' parent process is D% ' % os.getpid ())   # Get the current process number ID 
    P = pool (. 4)   # using the method creates a process pool 4 processes 
    for I in Range (. 1,. 6):   # to 4 of 5 task assignment process task number is 1,2,3,4,5 
        p.apply_async (task, args = (i,))   # apply_async is asynchronous non-blocking. # Make the task execution process pool function, pass the parameter is i 
    # means: do not wait for the current process is finished, ready to carry out the process of switching system according to schedule. 
    Print (' Wait for all child processes to finish ... ' ) 
    p.close ()   # close the process pool, because behind you join must ensure that the child is no longer running around 
    # the time.sleep (2) 
    # p.join () # make all the process ends with everyone waiting for another home for dinner 
    Print ( " all child processes to finish up ' )

 

Guess you like

Origin www.cnblogs.com/zhichao123/p/11240842.html