Skip to content

Commit 3d77f04

Browse files
committed
add lock, multithreading, threadlocal samples
1 parent a787f80 commit 3d77f04

3 files changed

Lines changed: 77 additions & 0 deletions

File tree

py3/multitask/do_lock.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import time, threading
5+
6+
# 假定这是你的银行存款:
7+
balance = 0
8+
lock = threading.Lock()
9+
10+
def change_it(n):
11+
# 先存后取,结果应该为0:
12+
global balance
13+
balance = balance + n
14+
balance = balance - n
15+
16+
def run_thread(n):
17+
for i in range(100000):
18+
# 先要获取锁:
19+
lock.acquire()
20+
try:
21+
# 放心地改吧:
22+
change_it(n)
23+
finally:
24+
# 改完了一定要释放锁:
25+
lock.release()
26+
27+
t1 = threading.Thread(target=run_thread, args=(5,))
28+
t2 = threading.Thread(target=run_thread, args=(8,))
29+
t1.start()
30+
t2.start()
31+
t1.join()
32+
t2.join()
33+
print(balance)

py3/multitask/multi_threading.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import time, threading
5+
6+
# 新线程执行的代码:
7+
def loop():
8+
print('thread %s is running...' % threading.current_thread().name)
9+
n = 0
10+
while n < 5:
11+
n = n + 1
12+
print('thread %s >>> %s' % (threading.current_thread().name, n))
13+
time.sleep(1)
14+
print('thread %s ended.' % threading.current_thread().name)
15+
16+
print('thread %s is running...' % threading.current_thread().name)
17+
t = threading.Thread(target=loop, name='LoopThread')
18+
t.start()
19+
t.join()
20+
print('thread %s ended.' % threading.current_thread().name)

py3/multitask/use_threadlocal.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#!/usr/bin/env python3
2+
# -*- coding: utf-8 -*-
3+
4+
import threading
5+
6+
# 创建全局ThreadLocal对象:
7+
local_school = threading.local()
8+
9+
def process_student():
10+
# 获取当前线程关联的student:
11+
std = local_school.student
12+
print('Hello, %s (in %s)' % (std, threading.current_thread().name))
13+
14+
def process_thread(name):
15+
# 绑定ThreadLocal的student:
16+
local_school.student = name
17+
process_student()
18+
19+
t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')
20+
t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
21+
t1.start()
22+
t2.start()
23+
t1.join()
24+
t2.join()

0 commit comments

Comments
 (0)