import threading
import time
class Thread(threading.Thread):
def __init__(self, lock, count, result):
threading.Thread.__init__(self)
self.lock = lock
self.count = count
self.result = result
def run(self):
self.lock.acquire()
print('threading.get_native_id() :', threading.get_native_id())
print('threading.current_thread().name :',
threading.current_thread().name)
print('threading.get_ident() :', threading.get_ident(), '\n')
for i in range(0, self.count):
self.result[0] += 1
self.lock.release()
class Test:
def __init__(self):
self.lock = threading.Lock()
self.count = 100000
self.result = 0
def worker_1(self, arg1, arg2):
print('arg1 :', arg1)
print('arg2 :', arg2)
with self.lock:
for i in range(0, self.count):
self.result += 1
def worker_2(self, second):
print('\t~~~', threading.current_thread().name, 'start ~~~')
time.sleep(second)
print('\t~~~', threading.current_thread().name, 'end ~~~')
def run_1(self):
threads = []
for i in range(0, 2):
t = threading.Thread(target=self.worker_1, args=(1, 2))
t.start()
threads.append(t)
for t in threads:
t.join()
print('self.result :', self.result)
def run_2(self):
t1 = threading.Thread(target=self.worker_2,
name='dameon=False',
args=(1, ))
t1.start()
t2 = threading.Thread(target=self.worker_2,
name='daemon=True',
args=(2, ),
daemon=True)
t2.start()
def worker(lock, count, result):
with lock:
for i in range(0, count):
result[0] += 1
def way_1():
print('----- way_1 start -----')
threads = []
lock = threading.Lock()
count = 100000
result = [0]
for i in range(0, 2):
t = Thread(lock, count, result)
t.start()
threads.append(t)
for t in threads:
t.join()
print('result :', result)
print('----- way_1 end -----\n')
def way_2():
print('----- way_2 start -----')
Test().run_1()
print('----- way_2 end -----\n')
def way_3():
print('----- way_3 start -----')
threads = []
lock = threading.Lock()
count = 100000
result = [0]
for i in range(0, 2):
t = threading.Thread(target=worker, args=(lock, count, result))
t.start()
threads.append(t)
for t in threads:
t.join()
print('result :', result)
print('----- way_3 end -----\n')
def way_4():
print('----- way_4 start -----')
Test().run_2()
print('----- way_4 end -----\n')
if __name__ == '__main__':
print('__main__ start\n')
way_1()
way_2()
way_3()
way_4()
print('__main__ end')