Skip to content

Commit

Permalink
Import
Browse files Browse the repository at this point in the history
  • Loading branch information
mtesseract committed Mar 25, 2017
0 parents commit eab2cfb
Show file tree
Hide file tree
Showing 10 changed files with 341 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
dist
dist-*
cabal-dev
*.o
*.hi
*.chi
*.chs.h
*.dyn_o
*.dyn_hi
.hpc
.hsenv
.cabal-sandbox/
cabal.sandbox.config
*.prof
*.aux
*.hp
*.eventlog
.stack-work/
cabal.project.local
30 changes: 30 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
Copyright Moritz Schulte (c) 2016, 2017

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.

* Neither the name of Author name here nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# async-timer

Example:

let conf = defaultTimerConf & timerConfSetInitDelay 500 -- 500 ms
& timerConfSetInterval 1000 -- 1 s

withAsyncTimer conf $ \ timer -> do
forM_ [1..10] $ \_ -> do
timerWait timer
putStrLn "Tick"
2 changes: 2 additions & 0 deletions Setup.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import Distribution.Simple
main = defaultMain
47 changes: 47 additions & 0 deletions async-timer.cabal
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: async-timer
version: 0.1.2
synopsis: Support for timer based execution of IO actions
description: Please see README.md
homepage: https://github.com/mtesseract/async-timer
license: BSD3
license-file: LICENSE
author: Moritz Schulte
maintainer: [email protected]
copyright: 2016, 2017 Moritz Schulte
category: Concurrency
build-type: Simple
extra-source-files: README.md
cabal-version: >=1.10

library
hs-source-dirs: src
exposed-modules: Control.Concurrent.Async.Timer
, Control.Concurrent.Async.Timer.Unsafe
other-modules: Control.Concurrent.Async.Timer.Internal
build-depends: base >= 4.7 && < 5
, lifted-async
, classy-prelude
default-language: Haskell2010
default-extensions: NoImplicitPrelude
ghc-options: -Wall

test-suite async-timer-test
type: exitcode-stdio-1.0
hs-source-dirs: test
main-is: Spec.hs
build-depends: base
, classy-prelude
, async-timer
, HUnit
, test-framework
, test-framework-hunit
, containers
, criterion
ghc-options: -threaded -rtsopts -with-rtsopts=-N
default-language: Haskell2010
default-extensions: NoImplicitPrelude
, OverloadedStrings

source-repository head
type: git
location: https://github.com/mtesseract/async-timer
30 changes: 30 additions & 0 deletions src/Control/Concurrent/Async/Timer.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}

module Control.Concurrent.Async.Timer
( Timer
, defaultTimerConf
, timerConfSetInitDelay
, timerConfSetInterval
, withAsyncTimer
, timerWait
) where

import ClassyPrelude
import Control.Concurrent.Async.Timer.Internal

withAsyncTimer :: forall m b. (MonadBaseControl IO m, Forall (Pure m))
=> TimerConf -> (Timer -> m b) -> m b
withAsyncTimer conf io = do
mVar <- newEmptyMVar
let timer = Timer { timerMVar = mVar }
timerTrigger = void $ tryPutMVar mVar ()
initDelay' = toMicroseconds $ _timerConfInitDelay conf
interval' = toMicroseconds $ _timerConfInterval conf
timerThread = timerLoop (threadDelay initDelay')
(threadDelay interval')
timerTrigger
withAsync timerThread $ const (io timer)

where toMicroseconds x = x * (10 ^ (3 :: Int))
37 changes: 37 additions & 0 deletions src/Control/Concurrent/Async/Timer/Internal.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE InterruptibleFFI #-}
{-# LANGUAGE MultiParamTypeClasses #-}

module Control.Concurrent.Async.Timer.Internal where

import ClassyPrelude

-- | Sleep 'dt' milliseconds.
millisleep :: Int64 -> IO ()
millisleep dt = threadDelay (fromIntegral dt * 10 ^ (3 :: Int))

data TimerConf = TimerConf { _timerConfInitDelay :: Int
, _timerConfInterval :: Int }

defaultTimerConf :: TimerConf
defaultTimerConf = TimerConf { _timerConfInitDelay = 0
, _timerConfInterval = 1000 }

timerConfSetInitDelay :: Int -> TimerConf -> TimerConf
timerConfSetInitDelay n conf = conf { _timerConfInitDelay = n }

timerConfSetInterval :: Int -> TimerConf -> TimerConf
timerConfSetInterval n conf = conf { _timerConfInterval = n }

data Timer = Timer { timerMVar :: MVar () }

timerLoop :: MonadBaseControl IO m
=> m () -> m () -> m () -> m ()
timerLoop initDelay intervalDelay timerTrigger = do
initDelay
forever $ timerTrigger >> intervalDelay

timerWait :: MonadBaseControl IO m
=> Timer -> m ()
timerWait = void . takeMVar . timerMVar
31 changes: 31 additions & 0 deletions src/Control/Concurrent/Async/Timer/Unsafe.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}

module Control.Concurrent.Async.Timer.Unsafe
( Timer
, defaultTimerConf
, timerConfSetInitDelay
, timerConfSetInterval
, withAsyncTimer
, timerWait
) where

import ClassyPrelude
import qualified Control.Concurrent.Async.Lifted as Unsafe
import Control.Concurrent.Async.Timer.Internal

withAsyncTimer :: forall m b. (MonadBaseControl IO m)
=> TimerConf -> (Timer -> m b) -> m b
withAsyncTimer conf io = do
mVar <- newEmptyMVar
let timer = Timer { timerMVar = mVar }
timerTrigger = void $ tryPutMVar mVar ()
initDelay' = toMicroseconds $ _timerConfInitDelay conf
interval' = toMicroseconds $ _timerConfInterval conf
timerThread = timerLoop (threadDelay initDelay')
(threadDelay interval')
timerTrigger
Unsafe.withAsync timerThread $ const (io timer)

where toMicroseconds x = x * (10 ^ (3 :: Int))
66 changes: 66 additions & 0 deletions stack.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# This file was automatically generated by 'stack init'
#
# Some commonly used options have been documented as comments in this file.
# For advanced use and comprehensive documentation of the format, please see:
# http://docs.haskellstack.org/en/stable/yaml_configuration/

# Resolver to choose a 'specific' stackage snapshot or a compiler version.
# A snapshot resolver dictates the compiler version and the set of packages
# to be used for project dependencies. For example:
#
# resolver: lts-3.5
# resolver: nightly-2015-09-21
# resolver: ghc-7.10.2
# resolver: ghcjs-0.1.0_ghc-7.10.2
# resolver:
# name: custom-snapshot
# location: "./custom-snapshot.yaml"
resolver: lts-8.5

# User packages to be built.
# Various formats can be used as shown in the example below.
#
# packages:
# - some-directory
# - https://example.com/foo/bar/baz-0.0.2.tar.gz
# - location:
# git: https://github.com/commercialhaskell/stack.git
# commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a
# - location: https://github.com/commercialhaskell/stack/commit/e7b331f14bcffb8367cd58fbfc8b40ec7642100a
# extra-dep: true
# subdirs:
# - auto-update
# - wai
#
# A package marked 'extra-dep: true' will only be built if demanded by a
# non-dependency (i.e. a user package), and its test suites and benchmarks
# will not be run. This is useful for tweaking upstream packages.
packages:
- '.'
# Dependency packages to be pulled from upstream that are not in the resolver
# (e.g., acme-missiles-0.3)
extra-deps: []

# Override default flag values for local packages and extra-deps
flags: {}

# Extra package databases containing global packages
extra-package-dbs: []

# Control whether we use the GHC we find on the path
# system-ghc: true
#
# Require a specific version of stack, using version ranges
# require-stack-version: -any # Default
# require-stack-version: ">=1.2"
#
# Override the architecture used by stack, especially useful on Windows
# arch: i386
# arch: x86_64
#
# Extra directories used by stack for building
# extra-include-dirs: [/path/to/dir]
# extra-lib-dirs: [/path/to/dir]
#
# Allow a newer minor version of GHC than the snapshot specifies
# compiler-check: newer-minor
68 changes: 68 additions & 0 deletions test/Spec.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
module Main where

import ClassyPrelude
import Data.Function ((&))
import Test.Framework (Test, defaultMain, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit ((@?=))
import Criterion.Measurement
import Control.Concurrent.Async.Timer
import Data.Typeable

data MyException = MyException
deriving (Show, Typeable)

instance Exception MyException

main :: IO ()
main = do
cap <- getNumCapabilities
putStrLn ""
putStrLn $ "Cap = " ++ tshow cap
defaultMain tests

tests :: [Test.Framework.Test]
tests =
[ testGroup "1st Test Group"
[ testCase "1st Test" test1 ]
]

test1 :: IO ()
test1 = do
let conf = defaultTimerConf & timerConfSetInitDelay 0
& timerConfSetInterval 1000 -- ms

counter <- newIORef 0
times <- newIORef []

withAsyncTimer conf $ \ timer -> do
forM_ [1..10] $ \_ -> do
timerWait timer
void $ fork $ myAction counter times

threadDelay 1000
n <- readIORef counter
n @?= 10

ts <- readIORef times
let deltas = case ts of
[] -> []
_ : tsTail -> map (\ (a, b) -> a - b) $ zip ts tsTail

diff = sum deltas - 9
forM_ deltas (\ dt -> putStrLn $ "dt = " ++ tshow dt)
putStrLn $ "average dt = " ++ tshow diff
return ()

where myAction :: IORef Int -> IORef [Double] -> IO ()
myAction counter times = do
t <- getTime
n <- readIORef counter
if n == 10
then throwIO MyException
else return ()
let n' = n + 1
writeIORef counter n'
modifyIORef times (t :)
putStrLn $ "Tick no. " ++ tshow n' ++ " (t = " ++ tshow t ++ ")"
threadDelay 500000

0 comments on commit eab2cfb

Please sign in to comment.