python核心編程筆記4--多線程

來源:互聯網
上載者:User

標籤:import   div   img   http   end   pre   class   圖片   []   

單線程程式:

import timedef Sorry():    print "I‘m sorry!"    time.sleep(1)if __name__==‘__main__‘:    for i in range(5):        Sorry()

添加線程


import threading

def thread_job():
print ‘this is an added Thread,number is %s‘ % threading.current_thread()

if __name__ == ‘__main__‘:
added_thread = threading.Thread(target=thread_job)
added_thread.start()

join 等待線程結束之後再往下執行

import time,threadingdef thread_job():    print ‘T1 start\n‘    for i in range(10):        time.sleep(0.1)    print ‘T1 finish\n‘def mian():    added_thread = threading.Thread(target=thread_job,name=‘T1‘)    added_thread.start()    print ‘all done\n‘if __name__ == ‘__main__‘:    mian()
import time,threadingdef thread_job():    print ‘T1 start\n‘    for i in range(10):        time.sleep(0.1)    print ‘T1 finish\n‘def mian():    added_thread = threading.Thread(target=thread_job,name=‘T1‘)    added_thread.start()    added_thread.join()    print ‘all done\n‘if __name__ == ‘__main__‘:    mian()

Queue功能,因為線程中不能使用return

import time,threadingfrom queue import Queuedef job(l,q):    for i in range(len(l)):        l[i] = l[i]**2    q.put(l)def multithreading():    q = Queue()    threads = []    data = [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]    for i in range(4):        t = threading.Thread(target=job,args=(data[i],q))        t.start()        threads.append(t)    for thread in threads:        thread.join()    results = []    for _ in range(4):        results.append(q.get())    print resultsif __name__ == ‘__main__‘:    multithreading()

lock鎖

import threadingdef job1():    global A    for i in range(10):        A += 1        print ‘job1 %d‘ % Adef job2():    global A    for i in range(10):        A += 10        print ‘job2 %d‘ % Aif __name__ == ‘__main__‘:    A = 0    t1 = threading.Thread(target=job1)    t2 = threading.Thread(target=job2)    t1.start()    t2.start()    t1.join()    t2.join()
import threadingdef job1():    global A,lock    lock.acquire()    for i in range(10):        A += 1        print ‘job1 %d‘ % A    lock.release()def job2():    global A,lock    lock.acquire()    for i in range(10):        A += 10        print ‘job2 %d‘ % A    lock.release()if __name__ == ‘__main__‘:    lock = threading.Lock()    A = 0    t1 = threading.Thread(target=job1)    t2 = threading.Thread(target=job2)    t1.start()    t2.start()    t1.join()    t2.join()

ps:多線程不一定有效率,有GIL鎖的存在,python只能同一時間讓一個線程運算同一個運算

import threadingfrom queue import Queueimport copyimport timedef job(l, q):    res = sum(l)    q.put(res)def multithreading(l):    q = Queue()    threads = []    for i in range(4):        t = threading.Thread(target=job, args=(copy.copy(l), q), name=‘T%i‘ % i)        t.start()        threads.append(t)    [t.join() for t in threads]    total = 0    for _ in range(4):        total += q.get()    print(total)def normal(l):    total = sum(l)    print(total)if __name__ == ‘__main__‘:    l = list(range(1000000))    s_t = time.time()    normal(l*4)    print(‘normal: ‘,time.time()-s_t)    s_t = time.time()    multithreading(l)    print(‘multithreading: ‘, time.time()-s_t)

 

python核心編程筆記4--多線程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.