learnging_threading

原文来自于morvan python,
https://morvanzhou.github.io/tutorials/python-basic/threading

import threading
import time
print threading.active_count()
print threading.enumerate()
print threading.current_thread()
5
[<Thread(Thread-4, started daemon 1120)>, <ParentPollerWindows(Thread-3, started daemon 8708)>, <HistorySavingThread(IPythonHistorySavingThread, started 6580)>, <_MainThread(MainThread, started 9940)>, <Heartbeat(Thread-5, started daemon 11164)>]
<_MainThread(MainThread, started 9940)>
def thread_job(a,t):
    print "hello %s , welcome to the threading world!. " %a
    #print('This is a thread of %s' % threading.current_thread())
    print " %s starts. " %a
    for i in range(t):
        time.sleep(0.1)# 任务间隔0.1s
    print " %s ends. " %a

def main():
    thread1 = threading.Thread(target=thread_job,args=('Lily',10,))
    thread2 = threading.Thread(target=thread_job,args=('Bob',5,))# 定义线程 
    thread1.start()  # 让线程开始工作
    thread2.start()  # 让线程开始工作
    thread1.join()
    thread2.join()
    print "all done."

if __name__ == '__main__':
    main()
hello Lily , welcome to the threading world!. hello Bob , welcome to the threading world!. 

Lily starts.  Bob starts. 

Bob ends. 
Lily ends. 
all done.
def thread_job(a):
    for i in range(len(a)):
        a[i]=a[i]**2

#Notice, list object input for function is address input not value input
def main():
    data =  [[1,2,3],[3,4,5],[4,4,4],[5,5,5]]
    threads=[]
    for i in range(4):
        t = threading.Thread(target=thread_job,args=(data[i],))
        threads.append(t)
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print "all done."
    print data

if __name__ == '__main__':
    main()
all done.
[[1, 4, 9], [9, 16, 25], [16, 16, 16], [25, 25, 25]]
def job1():
    global A
    for i in range(10):
        A+=1
        print('job1',A)

def job2():
    global A
    for i in range(10):
        A+=10
        print('job2',A)

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()
('job1', 1) ('job2', 11)

('job2', 23)('job1', 12)

('job2', 34)('job1', 13)

('job2', 44)('job1', 24)

('job2', 56)('job1', 45)

('job1', 46)('job2', 66)

('job1', 67)('job2', 78)

('job1', 68)('job2', 90)

('job1', 79)('job2', 100)

('job1', 80)('job2', 110)




posted @ 2017-11-20 10:50  Hello_to_Sa's_world  阅读(118)  评论(0编辑  收藏  举报