import threading import time num = 0 lock = threading.Lock() def increment(): global num lock.acquire() # 获取锁 num += 1 lock.release() # 释放锁 threads = [] for i in range(10000): t = threading.Thread(target=increment) threads.append(t) t.start() end = time.time() print(end - start) for t in threads: t.join() 哪里有错
时间: 2024-03-21 10:39:29 浏览: 112
Intel.Threading.Building.Blocks.Jul.2007.pdf
代码中缺少了变量 start 的定义,应该在创建线程之前定义 start 变量并赋值为当前时间,以便计算线程执行时间。修改后的代码如下:
```
import threading
import time
num = 0
lock = threading.Lock()
def increment():
global num
lock.acquire() # 获取锁
num += 1
lock.release() # 释放锁
threads = []
start = time.time() # 定义 start 变量并赋值为当前时间
for i in range(10000):
t = threading.Thread(target=increment)
threads.append(t)
t.start()
for t in threads:
t.join()
end = time.time()
print(end - start)
```
注意,计算线程执行时间的代码应该在循环结束后执行,因为 join() 方法会阻塞主线程,直到所有子线程都执行完毕。
阅读全文