简体   繁体   中英

Why is this Dekker algorithm implementation working?

Dekker algorithm is supposed not to work on modern multicore processors because they reorder statements in order to improve performance. Sequential code execution is not warranted.

If that's correct, why is the following implementation working?

I'm running it on a MacBook Pro 2015 - Capitan OSX, if that says something.

Thanks in advance!

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

Output is:

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

This is Python code, invoking separate functions. These functions were compiled independently and the Python interpreter will not reorder them.

But more importantly, testing a program and observing the expected behavior is by no means a proof of correctness.

Python has what's called a global interpreter lock , which, since each thread must acquire the lock to execute Python statements, has the effect of enforcing sequential consistency for Python. As Yves Daoust points out, even in C, this code might happen to work anyway almost all of the time -- multithreaded correctness really cannot be determined empirically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM