帮我看看这段代码为什么运行不出来import threading import time class Library(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.book_num=0 def borrow(self): global book_count global lock while True: lock = threading.Lock() time.sleep(1) if book_count>0: lock.acquire() time.sleep(0.1) book_count-=1 # book_count=book_count-1 self.book_num+=1 lock.release() print(f"借走{self.book_num}本,现有图书{book_count}本") else: break def back(self): global book_count global lock while True: lock = threading.Lock() time.sleep(3) # time.sleep(0.1) lock.acquire() book_count += 1 # book_count=book_count+1 lock.release() self.book_num -= 1 print(f"归还{self.book_num}本,现有图书{book_count}本") book_count=100 result1=Library() result2=Library() result1.start() result2.start() result1.join()
时间: 2023-12-01 10:02:41 浏览: 73
Python RuntimeError: thread.__init__() not called解决方法
这段代码有几个问题:
1. 在 borrow 和 back 方法里面,每次 while 循环都会重新创建一个锁对象。应该在外部创建好锁对象,然后将锁对象传递给 borrow 和 back 方法。
2. 在 borrow 方法里面,调用了 lock.acquire() 方法获得锁,但是在程序执行完毕后没有调用 lock.release() 方法释放锁。这会导致程序出现死锁。
3. 在 back 方法里面,self.book_num 减去 1 的代码应该在 lock.release() 方法之前执行,否则会导致程序出现竞争条件。
下面是修改后的代码:
```python
import threading
import time
class Library(threading.Thread):
def __init__(self, lock):
threading.Thread.__init__(self)
self.book_num = 0
self.lock = lock
def borrow(self):
global book_count
while True:
time.sleep(1)
if book_count > 0:
self.lock.acquire()
time.sleep(0.1)
book_count -= 1
self.book_num += 1
print(f"借走{self.book_num}本,现有图书{book_count}本")
self.lock.release()
else:
break
def back(self):
global book_count
while True:
time.sleep(3)
self.lock.acquire()
self.book_num -= 1
book_count += 1
print(f"归还{self.book_num}本,现有图书{book_count}本")
self.lock.release()
book_count = 100
lock = threading.Lock()
result1 = Library(lock)
result2 = Library(lock)
result1.start()
result2.start()
result1.join()
```
阅读全文