threadingモジュール

2964 ワード

threading
# import time
# import threading
# begin = time.time()
#
# def foo(n):
#     print('foo%s'%n)
#     time.sleep(1)
#     print('end foo')
#
# def bar (n):
#     print('bar%s'%n)
#     time.sleep(3)
#     print('end bar')
#
# t1 = threading.Thread(target=foo,args=(1,))
#
# t2 = threading.Thread(target=bar,args=(2,))
#
# t1.start()
# t2.start()
#
# print('************')
# t1.join()
# t2.join()
#
# end = time.time()
# print(end - begin)

# python :
#        
#   if   io    ,      
#                 ,sorry, C。

import time
import  threading
from time import ctime,sleep

def music(func):
    for i in range(2):
        print('begin listening to %s.%s'%(func,ctime()))
        sleep(1)
        print('end listening %s' %ctime())

def move(func):
    for i in range(2):
        print('begin listening to %s.%s'%(func,ctime()))
        sleep(5)
        print('end listening  %s' %ctime())

threads = []
t1 = threading.Thread(target=music,args=('   ',))
threads.append(t1)
t2 = threading.Thread(target=move,args=('    ',))
threads.append(t2)

if __name__ == '__main__':
#  t2     
t2.setDaemon(True)
    for i in threads:
        i.start()
#IO  
    i.join()
    print('end...............%s' %ctime())

    :
begin listening to    .Thu Jan 23 10:50:11 2020
begin listening to     .Thu Jan 23 10:50:11 2020end...............Thu Jan 23 10:50:11 2020

end listening Thu Jan 23 10:50:12 2020
begin listening to    .Thu Jan 23 10:50:12 2020
end listening Thu Jan 23 10:50:13 2020
end listening  Thu Jan 23 10:50:16 2020
begin listening to     .Thu Jan 23 10:50:16 2020
end listening  Thu Jan 23 10:50:21 2020

#       
'''
import threading
import time
class foo (threading.Thread):
    def __init__(self,num):
        threading.Thread.__init__(self)
        self.num = num

    def run(self):
        print('running on num:%s' %self.num)
        time.sleep(3)
if __name__ == '__main__':
    t1 = foo(1)
    t2 = foo(2)
    t1.start()
    t2.start()
'''

シンクロロック
import threading
import time

num = 100
r = threading.Lock()  #   
def addNum():
    global num      #              
    r.acquire()     #     
    num -= 1
    r.release()     #     

thread_list = []
for i in range(100):
    t = threading.Thread(target=addNum)
    t.start()
    thread_list.append(t)
for i in thread_list:
    t.join()

print('final num:',num)

しんごうりょう
import threading,time
class myThread(threading.Thread):
    def run(self):
        if semaphore.acquire():
            print(self.name)

            time.sleep(3)
            semaphore.release()

if __name__=="__main__":
    semaphore = threading.BoundedSemaphore(5)       #      5   
    thr = []
    for i in range(33):
        thr.append(myThread())
    for t in thr:
        t.start()