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

时间:2016-01-02 19:50:58

标签: python multithreading algorithm concurrency python-multithreading

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()

输出是:

  

计数器值:1000000预期:1000000错误:0,000000%

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

Python具有所谓的global interpreter lock,由于每个线程必须获取锁以执行Python语句,因此具有强制Python的顺序一致性的效果。正如Yves Daoust指出的那样,即使在C语言中,这段代码几乎在所有时间都可能正常工作 - 多线程的正确性实际上无法凭经验确定。