1 from time import sleep,ctime 2 def talk(): 3 print("stark talk %r" %ctime()) 4 sleep(2) 5 def write(): 6 print("stark write %r" %ctime()) 7 sleep(3) 8 talk() 9 write() 10 print("all and! at %r" %ctime())
3、多線程python
1 from time import sleep,ctime 2 import threading 3 4 def talk(content,loop): 5 for i in range(loop): 6 print("stark talk %s %s" %(content,ctime())) 7 sleep(3) 8 9 def write(content,loop): 10 for i in range(loop): 11 print("stark write %s %s" %(content,ctime())) 12 sleep(5) 13 #定義和加載說和寫的線程 14 threads=[] 15 t1=threading.Thread(target=talk,args=('hello world',2)) 16 threads.append(t1) 17 t2=threading.Thread(target=write,args=('life is short you need python',2)) 18 threads.append(t2) 19 #執行多線程 20 for t in threads: 21 t.start() 22 for t in threads: 23 #線程守護 24 t.join() 25 print("all threads end! at %r" %ctime())
1 from time import sleep,ctime 2 import multiprocessing 3 4 def talk(content,loop): 5 for i in range(loop): 6 print("stark talk %s %s" %(content,ctime())) 7 sleep(2) 8 9 def write(content,loop): 10 for i in range(loop): 11 print("stark write %s %s" %(content,ctime())) 12 sleep(3) 13 #定義和加載說和寫的進程 14 process=[] 15 p1=multiprocessing.Process(target=talk,args=('hello world',2)) 16 process.append(p1) 17 p2=multiprocessing.Process(target=write,args=('life is short you need python',2)) 18 process.append(p2) 19 #調用進程 20 if __name__=='__main__': 21 for t in process: 22 t.start() 23 for t in process: 24 #進程守護 25 t.join() 26 print("all process end! at %r" %ctime())