from Hacker News

A threading riddle

by davidtgoldblatt on 6/29/15, 2:47 PM with 19 comments

  • by oconnore on 6/29/15, 8:20 PM

        import Control.Concurrent.STM
        import Control.Monad
        import Data.Vector
    
        type VecInts = Vector (TVar Int)
    
        newVecInts :: Int -> STM (VecInts)
        newVecInts s = generateM s (\_ -> newTVar 0)
    
        modifyVI :: VecInts -> Int -> Int -> STM ()
        modifyVI vi pos val = do
          writeTVar (vi ! pos) val
    
        waitUntilEqual :: VecInts -> Int -> Int -> STM ()
        waitUntilEqual vi p1 p2 = do
          a <- readTVar (vi ! p1)
          b <- readTVar (vi ! p2)
          when (a /= b) retry
  • by sdab on 6/30/15, 5:47 PM

    My c++ solution: https://gist.github.com/anonymous/7e6cc8f58e9cde1b6fda

    I believe it follows all of the requirements. There is one glaring flaw which is that it uses a condition variable per 'wait_until_equal' call, though it uses only N mutexes. So this doesn't fall under the N^2 primitives (in the case of many waits), though its unclear to me if thats an official rule.

    Im happy to listen to feedback or if someone sees an error.

  • by brlewis on 6/29/15, 9:35 PM

    This is an example of why I see node.js having more value in its single-threaded async architecture than in its capacity to use the same programming language on client and server.

    More generally, when you discover a tricky problem that would make a good interview question, oftentimes there's an architectural decision that would eliminate the problem.