python的多執行緒和多程序

2021-08-14 02:52:07 字數 2825 閱讀 7351

#from multiprocessing import process,multiprocessing

#import threading,time

#import os,time

#print(multiprocessing.cpu_count());

from multiprocessing import pool

import os, time, random

#cpu_count=multiprocessing.cpu_count()

def video_work(n):

print("video start")

for i in range(4):

print(' video:%s' % time.time())

print('video end')

def voice_work(n):

print('voice start')

for i in range(4):

print(' voice:%s' % time.time())

print('voice end')

def text_work(n):

print('text start')

for i in range(4):

print(' text:%s' % time.time())

print('text end')

if __name__=='__main__':

print("movie start")

p=pool(3)

print("movie end")

p.close()

p.join()

os._exit(0);

#下面是多執行緒

def video_work(n):

print("video start")

for i in range(4):

print(' video:%s' % time.time())

print('video end')

def voice_work(n):

print('voice start')

for i in range(4):

print(' voice:%s' % time.time())

print('voice end')

def text_work(n):

print('text start')

for i in range(4):

print(' text:%s' % time.time())

print('text end')

vi=threading.thread(target=video_work, args=(5,))

vo=threading.thread(target=voice_work, args=(5,))

te=threading.thread(target=text_work, args=(5,))

vi.start()

vo.start()

te.start()

vi.join()

vo.join()

te.join()

下面賦上程序和執行緒的結果對比:

執行緒:
video start

video:1514341023.8669481

video:1514341023.866982

video:1514341023.8669922

video:1514341023.867

video end

voice start

voice:1514341023.867081

voice:1514341023.867098

voice:1514341023.867109

voice:1514341023.867122

voice end

text start

text:1514341023.867318

text:1514341023.86733

text:1514341023.8673432

text:1514341023.8673549

text end

[finished in 0.2s]

程序:
movie start

movie end

video start

video:1514340229.850396

video:1514340229.850455

video:1514340229.850463

voice start

video:1514340229.8504698

video end

voice:1514340229.850525

voice:1514340229.8505862

voice:1514340229.8505971

voice:1514340229.850604

voice end

text start

text:1514340229.851182

text:1514340229.85122

text:1514340229.85123

text:1514340229.851239

text end

[finished in 0.3s]

程序是真正的做到了併發。而多執行緒併發因為鎖的原因,並不能做到這一點。

python 多執行緒 和 多程序

單執行緒例子 usr bin python coding utf 8 name danxiancheng.py import time import threading def loop num,sec print loop s start num,time.strftime y m d h m s...

python多執行緒和多程序

pool 感謝多執行緒和多程序最大的不同在於,多程序中,同乙個變數,各自有乙份拷貝存在於每個程序中,互不影響 而多執行緒中,所有變數都由所有執行緒共享,所以,任何乙個變數都可以被任何乙個執行緒修改,因此,執行緒之間共享資料最大的危險在於多個執行緒同時改乙個變數,把內容給改亂了。python中,多執行...

多程序和多執行緒python

coding utf8 import threading import time class mop floor threading.thread def init self super mop floor,self init def run self print 我要拖地了 time.sleep ...