forked from wjw12/python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadlock.py
More file actions
Latest commit
47 lines (39 loc) · 1.16 KB
/
Copy paththreadlock.py
File metadata and controls
47 lines (39 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!python2
#coding=utf-8
importthreading
importtime
classmyThread (threading.Thread):
def__init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID=threadID
self.name=name
self.counter=counter
defrun(self):
print"Starting "+self.name
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 释放锁
threadLock.release()
defprint_time(threadName, delay, counter):
whilecounter:
time.sleep(delay)
print"%s: %s"% (threadName, time.ctime(time.time()))
counter-=1
threadLock=threading.Lock()
threads= []
# 创建新线程
thread1=myThread(1, "Thread-1", 1)
thread2=myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
fortinthreads:
t.join()
print"Exiting Main Thread"