Please read the new rule regarding the restriction on the use of AI tools. ×

N-ary Locking Problem

Revision en2, by BitwiseXOR, 2024-09-20 13:00:17

I’ve been working on this problem for several days but still struggle.

The problem involves an N-ary tree (where each non-leaf node has exactly n children). The goal is to implement a Lock() operation with the following rules:

Lock(string X, int id):

If node X is already locked, you cannot lock it, so return false. If any of X's descendants are locked, you cannot lock it, so return false. If any of X's ancestors are locked, you cannot lock it, so return false. If none of the above conditions are met, lock node X with the given ID and return true.

You are required to handle M queries of the Lock() operation on a multi-core machine, allowing M threads to run the Lock() function concurrently. However, since the function involves multiple internal checks, locking two nodes simultaneously can result in race conditions.

How would you make the Lock() function thread-safe?

Tags trees, queries on tree, threads, multi-threading

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en3 English BitwiseXOR 2024-09-20 13:03:16 5
en2 English BitwiseXOR 2024-09-20 13:00:17 16 Tiny change: 'e given ID.\n\nYou a' -> 'e given ID and return true.\n\nYou a'
en1 English BitwiseXOR 2024-09-20 12:58:52 900 Initial revision (published)