Python 3.X 基础(三)

时间:2022-01-19 04:02:46

多线程

from time import ctime,sleep
import threading

def talk(content,loop):
    for i in range(loop):
        print("start talk:%s%s" %(content,ctime()))
        sleep(2)

def write(content,loop):
    for i in range(loop):
        print("start write:%s%s" %(content,ctime()))
        sleep(2)

threads=[]
t1=threading.Thread(target=talk,args=('hello world',2))
threads.append(t1)

t2=threading.Thread(target=write,args=('life is short,you need python',2))
threads.append(t2)

if __name__=='__main__':
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print("All the end %r" %ctime())
多进程

from time import ctime,sleep
import multiprocessing

def talk(content,loop):
    for i in range(loop):
        print("start talk:%s%s" %(content,ctime()))
        sleep(2)

def write(content,loop):
    for i in range(loop):
        print("start write:%s%s" %(content,ctime()))
        sleep(2)

process=[]
p1=multiprocessing.Process(target=talk,args=('hello world',2))
process.append(p1)

p2=multiprocessing.Process(target=write,args=('life is short,you need python',2))
process.append(p2)

if __name__=='__main__':
    for p in process:
        p.start()
    for p in process:
        p.join()
    print("All the end %r" %ctime())