第1关:线程同步之报数

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
# -*- coding: utf-8 -*-

import threading
import time
lock = threading.Lock()
class mythread(threading.Thread):
x = 0
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global x
#*********begin*********#
lock.acquire()
mythread.x += 1
print(mythread.x,end='')
time.sleep(0.1)
lock.release()
#********* end*********#

num = input()
t1 = []
for i in range(int(num)):
t = mythread()
t1.append(t)
x = 0
for i in t1:
i.start()

第2关:线程同步之生产者-消费者问题

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
48
49
50
51
52
53
54
55
56
# -*- coding: utf-8 -*-

import threading
import time
con = threading.Condition()
class Producer(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self):
global x
#*********begin*********#
with con:
while x >= self.num:
con.wait()
for i in range(x, self.num+1):
if(i!=self.num):
print(i, end=" ")
else:
print(i)
x += 1
time.sleep(0.1)
con.notify()

#********* end*********#

class Consumer(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self):
global x
#*********begin*********#
with con:
while x <= 0:
con.wait()
for i in range(self.num,-1, -1):
if(i!=-1):
print(i, end=" ")
else:
print(i)
x -= 1
time.sleep(0.1)
con.notify_all()
#********* end*********#


num = input()
x = 0
num = int(num)
p = Producer(num)
c = Consumer(num)
p.start()
c.start()
p.join()
c.join()