gpt4 book ai didi

python - 为什么这个 Dekker 算法实现有效?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:06:33 28 4
gpt4 key购买 nike

Dekker 算法应该不适用于现代多核处理器,因为它们会重新排序语句以提高性能。不保证顺序代码执行。

如果那是正确的,为什么下面的实现有效?

我在 MacBook Pro 2015 - Capitan OSX 上运行它,如果有的话。

提前致谢!

# Dekker algorithm
from threading import Thread

THREADS_AMOUNT = 2
MAX_COUNT_AMOUNT = 10000000
COUNT_PER_THREAD = MAX_COUNT_AMOUNT/THREADS_AMOUNT

count = 0


class Worker(Thread):

turn = 0
want_status = [False, False]

def __init__(self, id):
self.me = id
self.him = (id + 1) % 2
Thread.__init__(self)

def run(self):
for count in range(COUNT_PER_THREAD):
self.pre_protocol()
self.critical_section()
self.post_protocol()

def pre_protocol(self):
Worker.want_status[self.me] = True
while Worker.want_status[self.him]:
if Worker.turn == self.him:
Worker.want_status[self.me] = False
while Worker.want_status[self.him]:
pass
Worker.want_status[self.me] = True

def critical_section(self):
global count
count += 1

def post_protocol(self):
Worker.turn = self.him
Worker.want_status[self.me] = False


threads = []


def main():
create_threads()
start_threads()
join_threads()
output_result()


def create_threads():
for id in range(THREADS_AMOUNT):
new_thread = Worker(id)
threads.append(new_thread)


def start_threads():
for thread in threads:
thread.start()


def join_threads():
for thread in threads:
thread.join()


def output_result():
print("Counter value: {} -- Expected: {}".format(count, MAX_COUNT_AMOUNT))

if __name__ == "__main__":
main()

输出是:

Counter value: 1000000 Expected: 1000000 Error: 0,000000%

最佳答案

这是 Python 代码,调用单独的函数。这些函数是独立编译的,Python 解释器不会对它们重新排序。

但更重要的是,测试程序并观察预期行为绝不是正确性的证明。

关于python - 为什么这个 Dekker 算法实现有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570052/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com