File tree Expand file tree Collapse file tree 4 files changed +97
-0
lines changed Expand file tree Collapse file tree 4 files changed +97
-0
lines changed Original file line number Diff line number Diff line change
1
+ import socket
2
+
3
+
Original file line number Diff line number Diff line change
1
+ from contextlib import contextmanager
2
+ import time
3
+
4
+ @contextmanager
5
+ def timer (func ):
6
+ try :
7
+ start = time .time ()
8
+ yield func ()
9
+ finally :
10
+ end = time .time ()
11
+ print (end - start )
12
+
13
+
14
+ def func ():
15
+ for i in range (9999999 ):
16
+ pass
17
+ time .sleep (1 )
18
+
19
+ with timer (func ) as timer :
20
+ pass
Original file line number Diff line number Diff line change
1
+ import threading
2
+ import time
3
+
4
+
5
+ class HtmlSppier (threading .Thread ):
6
+ def __init__ (self , url , sem ):
7
+ super ().__init__ ()
8
+ self .sem = sem
9
+ self .url = url
10
+
11
+ def run (self ):
12
+ time .sleep (2 )
13
+ print ('download html success' )
14
+ self .sem .release ()
15
+
16
+ class UrlProducer (threading .Thread ):
17
+ def __init__ (self ,sem ):
18
+ super ().__init__ ()
19
+ self .sem = sem
20
+
21
+
22
+ def run (self ):
23
+ for i in range (20 ):
24
+ self .sem .acquire ()
25
+ html_thread = HtmlSppier (f'http://www.qq.com/pn={ i } ' ,self .sem )
26
+ html_thread .start ()
27
+
28
+
29
+ if __name__ == '__main__' :
30
+ sem = threading .Semaphore (3 )
31
+ url_produce = UrlProducer (sem )
32
+ url_produce .start ()
Original file line number Diff line number Diff line change
1
+ from threading import Thread , Condition
2
+
3
+
4
+ class T1 (Thread ):
5
+ def __init__ (self , con ):
6
+ super ().__init__ ()
7
+ self .con = con
8
+
9
+ def run (self ):
10
+ with self .con :
11
+ print (1 )
12
+ self .con .notify ()
13
+ self .con .wait ()
14
+ print (3 )
15
+ self .con .notify ()
16
+ self .con .wait ()
17
+
18
+
19
+ class T2 (Thread ):
20
+ def __init__ (self , con ):
21
+ super ().__init__ ()
22
+ self .con = con
23
+
24
+ def run (self ):
25
+ with self .con :
26
+ self .con .wait ()
27
+ print (2 )
28
+ self .con .notify ()
29
+ self .con .wait ()
30
+ print (4 )
31
+ self .con .notify ()
32
+
33
+
34
+
35
+
36
+ if __name__ == '__main__' :
37
+ con = Condition ()
38
+ thread1 = T1 (con )
39
+ thread2 = T2 (con )
40
+
41
+ thread2 .start ()
42
+ thread1 .start ()
You can’t perform that action at this time.
0 commit comments