|
| 1 | +import _thread |
| 2 | +import time |
| 3 | +import threading |
| 4 | +import PikaStdLib |
| 5 | +# 共享资源 |
| 6 | +shared_resource = 0 |
| 7 | + |
| 8 | +# 互斥锁 |
| 9 | +mutex = threading.Lock() |
| 10 | + |
| 11 | +# 线程函数 |
| 12 | + |
| 13 | +finished = 0 |
| 14 | + |
| 15 | + |
| 16 | +def thread_function(name, delay): |
| 17 | + global shared_resource |
| 18 | + global mutex, finished |
| 19 | + print("delay : %s" % str(delay)) |
| 20 | + k = 0 |
| 21 | + i = 0 |
| 22 | + mem = PikaStdLib.MemChecker() |
| 23 | + for i in range(5): |
| 24 | + # while 1: |
| 25 | + |
| 26 | + try: |
| 27 | + # 获取互斥锁 |
| 28 | + print("%s try to acquire lock. #1" % name) |
| 29 | + res = mutex.acquire(True, None) |
| 30 | + print("res: %s" % str(res)) |
| 31 | + if 1: # 测试RLock或者Lock的超时加上 |
| 32 | + print("%s try to acquire lock. #2" % name) |
| 33 | + res = mutex.acquire(True, 0.5) |
| 34 | + print("res: %s" % str(res)) |
| 35 | + if res: |
| 36 | + print("%s acquire lock SUCC." % name) |
| 37 | + else: |
| 38 | + print("%s acquire lock FAIL." % name) |
| 39 | + # 打印当前线程名称和共享资源的值 |
| 40 | + print("Thread %s: Iteration %d, Shared Resource: %d" % |
| 41 | + (name, i, shared_resource)) |
| 42 | + |
| 43 | + # 更新共享资源 |
| 44 | + shared_resource += 1 |
| 45 | + |
| 46 | + # 模拟工作时间 |
| 47 | + |
| 48 | + time.sleep(delay) |
| 49 | + print("wake") |
| 50 | + |
| 51 | + # 释放互斥锁 |
| 52 | + mutex.release() |
| 53 | + mutex.release() |
| 54 | + k += 1 |
| 55 | + |
| 56 | + print("%s i = %d." % (name, i)) |
| 57 | + # print('mem used now:') |
| 58 | + # mem.now() |
| 59 | + |
| 60 | + except: |
| 61 | + print("------------- error ---------------") |
| 62 | + |
| 63 | + print("%s exit , at last, i = %d." % (name, k)) |
| 64 | + finished += 1 |
| 65 | + |
| 66 | +# 主函数 |
| 67 | + |
| 68 | + |
| 69 | +def main(): |
| 70 | + # 创建第一个线程 |
| 71 | + _thread.start_new_thread(thread_function, ("Thread-1", 0.1)) |
| 72 | + time.sleep(0.5) |
| 73 | + # 创建第二个线程 |
| 74 | + _thread.start_new_thread(thread_function, ("Thread-2", 0.2)) |
| 75 | + |
| 76 | + # 主线程等待子线程结束 |
| 77 | + # 由于 _thread 没有 join 方法,我们通过 sleep 来模拟等待 |
| 78 | + # time.sleep(60) |
| 79 | + while finished < 2: |
| 80 | + time.sleep(1) |
| 81 | + |
| 82 | + |
| 83 | +main() |
0 commit comments