此代码不应该总是有效,但它在我的机器上有效!
from datetime import datetime
import threading
# Create a shared resource
shared_resource = 0
# Create a lock
# lock = threading.Lock()
# Define a function that will access the shared resource
def update_shared_resource():
global shared_resource
for i in range(10000000):
# Acquire the lock
# lock.acquire()
shared_resource += 1
# Release the lock
# lock.release()
# Create two threads to run the function concurrently
thread1 = threading.Thread(target=update_shared_resource)
thread2 = threading.Thread(target=update_shared_resource)
# Start the threads
thread1.start()
thread2.start()
# Wait for the threads to finish
thread1.join()
thread2.join()
# Print the final value of the shared resource
print(str(datetime.now()) + " Shared resource value: ", shared_resource)
由于竞争条件,多次运行这段代码应该会产生随机结果,但在我的机器上,它每次总是给出正确的结果! (我在其他机器和在线编译器上试过,有的按预期工作,有的和我的机器一样!) 编译器是否在幕后做了一些事情?我的机器是不是很快!?!!