I passed this as part of the school assignment, and the person who marked it mentioned that this section is not thread safe.
The purpose was to create a multi-threaded socket server in python that took a number and returned the Fibonacci value of that number. My approach was to memorize calculations by sharing a dictionary between each of the threads.
Here is the code (with error handling and so remote for brevity)
from socketserver import ThreadingMixIn, TCPServer, BaseRequestHandler class FibonacciThreadedTCPServer(ThreadingMixIn, TCPServer): def __init__(self, server_address): TCPServer.__init__(self, server_address, FibonacciThreadedTCPRequestHandler, bind_and_activate=True)
I understand that reads and writes occur in the calc_fib method, and this usually means that the code is not thread safe. However, in this case, I consider it possible to prove that the code will always provide predictable results.
Is the fact that reading and writing can occur at the same time so as not to be considered thread safe? Or something is considered thread safe if it always returns the result with reliability.
Why I think this code will always give reliable results:
Reading will never occur at any index in the dictionary until writing occurs there.
Any subsequent record in any given index will contain the same number as previous records, therefore, regardless of when the read / write sequence occurs, it will always receive the same data.
I tested this by adding random dreams between each operation and making requests with several hundred threads at the same time, and the correct answer was already returned during my test.
Any thoughts or criticism will be appreciated. Thanks.
source share