Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,10 @@ takeInterval i value = withStream value $ drain . Stream.takeInterval i
-- inspect $ 'takeInterval `hasNoType` ''D.Step
#endif

{-# NOINLINE takeInterval_ #-}
takeInterval_ :: Double -> Int -> IO ()
takeInterval_ i value = withStream value $ drain . Stream.takeInterval_ i

{-# NOINLINE dropInterval #-}
dropInterval :: Double -> Int -> IO ()
dropInterval i value = withStream value $ drain . Stream.dropInterval i
Expand All @@ -258,6 +262,7 @@ timeBenchmarks :: BenchEnv -> Int -> [Benchmark]
timeBenchmarks _env size =
[ benchIO "parTapCount 1 second" (pollCounts size)
, benchIO "takeInterval-all" (takeInterval 10000 size)
, benchIO "takeInterval_-all" (takeInterval_ 10000 size)
, benchIO "dropInterval-all" (dropInterval 10000 size)
]

Expand Down
77 changes: 76 additions & 1 deletion src/Streamly/Internal/Data/Stream/Time.hs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ module Streamly.Internal.Data.Stream.Time

-- * Trimming
, takeInterval
, takeInterval_
, takeLastInterval
, dropInterval
, dropLastInterval
Expand Down Expand Up @@ -59,14 +60,19 @@ where

#include "inline.hs"

import Control.Exception (assert)
import Control.Concurrent (ThreadId, forkIOWithUnmask, killThread, yield)
import Control.Exception (assert, mask_)
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Heap (Entry(..))
import Data.Int (Int64)
import Data.IORef (IORef, mkWeakIORef, newIORef, readIORef, writeIORef)
import Data.Kind (Type)
import Data.Map (Map)
import Data.Maybe (isJust, isNothing)
import Data.Proxy (Proxy(..))
import Fusion.Plugin.Types (Fuse(..))
import System.Mem.Weak (deRefWeak)
import Streamly.Data.Fold (Fold)
import Streamly.Data.Array (Unbox)
import Streamly.Internal.Data.Array (Array)
Expand Down Expand Up @@ -203,6 +209,75 @@ takeInterval d xs
, Stream.fromEffect (Stream.sleep d >> return Nothing)
]

{-# ANN type TakeIntervalState Fuse #-}
data TakeIntervalState s
Comment thread
GuillaumedeVolpiano marked this conversation as resolved.
Resolved
= TakeIntervalInit s
| TakeIntervalRun !Int !(IORef Bool) !ThreadId s

-- | Like 'takeInterval' but faster, with a weaker guarantee about the time at
-- which the stream ends, and without requiring 'MonadAsync'.
--
-- An element is yielded if the evaluation generating it starts before the end
-- of the interval, whenever it finishes. The evaluation of the stream is not
-- interrupted at the end of the interval: if it blocks, the stream does not
-- end until it returns.
--
-- The stream is evaluated in the thread of the consumer. Another thread is
-- forked only to keep the time. It ends at the end of the interval, or when
-- the stream ends if that happens earlier. If the stream is abandoned before
-- it ends, the thread is killed when the stream is garbage collected.
--
-- /Pre-release/
{-# INLINE takeInterval_ #-}
takeInterval_ :: MonadIO m => Double -> Stream m a -> Stream m a
takeInterval_ d (Stream.Stream step state) =
Stream.Stream step1 (TakeIntervalInit state)
Comment thread
GuillaumedeVolpiano marked this conversation as resolved.
Resolved

where

-- The timer thread gets to run only when the thread evaluating the stream
-- yields the CPU, which a fused loop that does not allocate never does on
-- its own. So we yield explicitly, once in this many steps.
yieldCount :: Int
yieldCount = 1000

-- A one-shot timer thread sets a flag at the end of the interval, reading
-- the flag is cheaper than reading the clock for each element.
--
-- The timer thread holds only a weak reference to the flag, so that the
-- flag becomes unreachable when the stream is abandoned, and its finalizer
-- kills the thread. Asynchronous exceptions are masked until the finalizer
-- is installed, otherwise the thread could be left without one.
startTimer = mask_ $ do
ref <- newIORef False
weak <- mkWeakIORef ref (return ())
tid <- forkIOWithUnmask $ \unmask -> unmask $ do
Stream.sleep d
deRefWeak weak >>= mapM_ (`writeIORef` True)
_ <- mkWeakIORef ref (killThread tid)
return (ref, tid)

{-# INLINE_LATE step1 #-}
step1 _ (TakeIntervalInit st)
| not (d > 0) = return Stop
| otherwise = do
(ref, tid) <- liftIO startTimer
-- Let the timer thread start, the interval begins now.
liftIO yield
return $ Skip $ TakeIntervalRun yieldCount ref tid st
step1 gst (TakeIntervalRun n ref tid st) = do
when (n <= 0) $ liftIO yield
expired <- liftIO $ readIORef ref
if expired
Comment thread
GuillaumedeVolpiano marked this conversation as resolved.
Resolved
then return Stop

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need killThread here.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The flag is set by the timer's thread's last action, so the thread is already dying. Adding it would be harmless, though, so happy to comply if you insist ;)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's right.

else do
let n1 = if n <= 0 then yieldCount else n - 1
r <- step gst st
case r of
Yield x s -> return $ Yield x (TakeIntervalRun n1 ref tid s)
Skip s -> return $ Skip (TakeIntervalRun n1 ref tid s)
Stop -> liftIO (killThread tid) >> return Stop

-- | Take time interval @i@ seconds at the end of the stream.
--
-- O(n) space, where n is the number elements taken.
Expand Down
53 changes: 53 additions & 0 deletions test/Streamly/Test/Data/Stream/Prelude/Time.hs
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,43 @@ dropIntervalHuge d =
$ Stream.dropInterval d
$ Stream.fromList [1..10]

takeInterval_Of :: Double -> IO [Int]
takeInterval_Of d =
Stream.fold Fold.toList
$ Stream.takeInterval_ d
$ Stream.fromList [1..10]

takeInterval_Prefix :: IO Bool
takeInterval_Prefix = do
xs <-
Stream.fold Fold.toList
$ Stream.takeInterval_ shortInterval slowEnumeration
return $ not (null xs) && xs == [1..length xs]

-- The second element is generated after the end of the interval, by an action
-- started before it. takeInterval_ does not interrupt the action, and yields
-- the element. No action is started after the end of the interval.
takeInterval_Blocked :: IO [Int]
takeInterval_Blocked =
Stream.fold Fold.toList
$ Stream.takeInterval_ shortInterval
$ Stream.mapM (\x -> when (x > 1) (threadDelay 300000) >> return x)
$ Stream.fromList [1..10]

-- The loop does not allocate, so the timer thread of takeInterval_ runs only if
-- the loop yields the CPU. A loop that never yields cannot be interrupted, so
-- the stream is finite: if the timer thread does not run, the loop ends by
-- itself after several seconds, having taken all the elements. The number of
-- elements must fit in an Int of 32 bits, for the JavaScript backend.
takeInterval_Spin :: IO Bool
takeInterval_Spin = do
let total = 2000000000 :: Int
n <-
Stream.fold Fold.length
$ Stream.takeInterval_ shortInterval
$ Stream.enumerateFromTo 1 total
return $ n < total

-- The stream is endless, so this returns only if takeInterval ends it. The
-- elements taken must be the beginning of the stream.
takeIntervalPrefix :: IO Bool
Expand Down Expand Up @@ -191,6 +228,22 @@ main = hspec
(takeIntervalOf nan `shouldReturn` [])
it "takeInterval ends a blocked stream after the interval"
(takeIntervalBlocked `shouldReturn` Just [1])
it "takeInterval_ takes all the elements within the interval"
(takeInterval_Of longInterval `shouldReturn` [1..10])
it "takeInterval_ takes all the elements if the interval is infinite"
(takeInterval_Of (1/0) `shouldReturn` [1..10])
it "takeInterval_ ends the stream after the interval"
(takeInterval_Prefix `shouldReturn` True)
it "takeInterval_ takes nothing if the interval is zero"
(takeInterval_Of 0 `shouldReturn` [])
it "takeInterval_ takes nothing if the interval is negative"
(takeInterval_Of (-1) `shouldReturn` [])
it "takeInterval_ takes nothing if the interval is NaN"
(takeInterval_Of nan `shouldReturn` [])
it "takeInterval_ yields the element of an action in progress"
(takeInterval_Blocked `shouldReturn` [1,2])
it "takeInterval_ ends a loop that never yields the CPU"
(takeInterval_Spin `shouldReturn` True)
it "dropInterval drops nothing if the interval is zero"
(dropIntervalOf 0 `shouldReturn` [1..10])
it "dropInterval drops nothing if the interval is negative"
Expand Down
Loading