提问人:fm_0091 提问时间:4/18/2023 更新时间:4/18/2023 访问量:21
线程创建和实现互斥通过使用切换
Thread creation and implementation of mutual exclusion by use switching
问:
如果可能的话,我希望得到一点帮助。
我需要找到执行任务的时间(以秒为单位)。
我仍在学习用 Python 编程,我下面的代码无法正常工作。我可以修改或更正哪些内容?
import threading
import time
x = 0
turn = 0
def entra_cs(num_tasks):
global turn
while turn != num_tasks:
pass
def sai_cs(num_tasks):
global turn
turn = (turn + 1) % num_tasks
def incrementa():
global x
x = x + 1
def thread_task(num_tasks):
for _ in range(10):
entra_cs(num_tasks)
incrementa()
sai_cs(num_tasks)
def main_task():
global x
x = 0
t1 = threading.Thread(target=thread_task, args=(1,))
t2 = threading.Thread(target=thread_task, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()
if __name__ == "__main__":
comeco = time.time()
for i in range(10):
main_task()
print("Iteration {0}: x = {1}".format(i, x))
fim = time.time()
print('Duration in seconds -', comeco - fim)
答: 暂无答案
评论