0

How to make a thread run indefinitely in Haskell?

Refael Sheinker
  • 713
  • 7
  • 20
  • @Noughtmare No, it does not. There, it sleeps a thread for a specific time, I want the behavior of C#'s Thread.Sleep() - without parameter - sleep indefinitely. I've edited the question to be more clear. – Refael Sheinker Mar 11 '23 at 20:22
  • 1
    Are you using multiple threads and want one of them to sleep? In that case, how did you create those threads in Haskell? – Bergi Mar 11 '23 at 21:45
  • 1
    When you're asking how to do something, it's always better to specify the functionality you want instead of just saying "I want an equivalent of this other thing from another language". At most a reference to another language should be a secondary clarification. There are lots of people who would know how to do what you want in Haskell but who don't know C#, and so don't know that they know what you want. And likewise (since you're self-answering), likely other people in future will want the same thing who don't know C#, so the question is more useful if it doesn't depend on that. – Ben Mar 11 '23 at 23:31
  • @Ben, you are correct. I rephrased the question. – Refael Sheinker Mar 12 '23 at 05:15
  • @Bergi I am using multiply threads in Haskell. I created them with `forkIO`. – Refael Sheinker Mar 12 '23 at 05:15

1 Answers1

-1

Here is an example:

main :: IO ()
main = do
  print "Waiting for ever"
  forever $ threadDelay maxBound
Refael Sheinker
  • 713
  • 7
  • 20
  • On some older versions of GHC + MacOS, `threadDelay maxBound` would segfault the process. I'm sure it's fixed by now, but it still made me paranoid of passing large numbers to `threadDelay`. – Carl Mar 11 '23 at 21:36
  • 1
    This seems mildly unlikely to be the right way to accomplish whatever it is you're trying to do. I can think of basically two applications. If you're trying to keep the `main` thread running so that the program doesn't end prematurely, the right way is to share an `MVar` between the threads that are actually doing something and `main`, and to have `main` wait until the `MVar` is filled by each thread you want to survive. If you want a thread to sleep until it's thrown an asynchronous exception, the right way is to share an `MVar` or `TVar` between thrower and receiver and wait on that instead. – Daniel Wagner Mar 12 '23 at 04:21
  • @Carl You are correct, but it's long been fixed now. – Refael Sheinker Mar 12 '23 at 05:16
  • @DanielWagner I came across it here: https://hackage.haskell.org/package/fsnotify-0.4.1.0/docs/System-FSNotify.html. Look at the example at the top of the page. – Refael Sheinker Mar 12 '23 at 05:18
  • @RefaelSheinker Presumably the event to watch for to fill your shared `MVar` would be the `WatchedDirectoryRemoved` event. Example code is traditionally as simple as possible -- not as best-practice as possible. – Daniel Wagner Mar 12 '23 at 05:54