为什么每隔两秒读一个不断变化的文件,并给出相同的值?(Why is reading a constantly changing file twice a second apart giving the

编程入门 行业动态 更新时间:2024-10-25 07:20:35
为什么每隔两秒读一个不断变化的文件,并给出相同的值?(Why is reading a constantly changing file twice a second apart giving the same value?)

我刚刚在Haskell中写了这一行,看看我每秒使用多少带宽:

>>> import Control.Monad (forever) >>> import Control.Concurrent (threadDelay) -- microseconds; 10^6μs = 1s >>> let f = "/sys/class/net/wlan0/statistics/rx_bytes" in forever $ readFile f >>= \a -> threadDelay (10^6) >> readFile f >>= \b -> print (read b - read a) 0 0 0 0 0 0 0 0 0

但它总是说0.我在Bash中并行运行了一行代码,这表明在这段时间内文件确实在变化:

$ f=/sys/class/net/wlan0/statistics/rx_bytes; while true; do a=`cat $f`; sleep 1; echo $((`cat $f`-a)); done 98 98 2132 3178 230 306 98 98 729

为什么Haskell没有看到它改变?

I just wrote this one liner in Haskell to see the how much bandwidth I'm using per second:

>>> import Control.Monad (forever) >>> import Control.Concurrent (threadDelay) -- microseconds; 10^6μs = 1s >>> let f = "/sys/class/net/wlan0/statistics/rx_bytes" in forever $ readFile f >>= \a -> threadDelay (10^6) >> readFile f >>= \b -> print (read b - read a) 0 0 0 0 0 0 0 0 0

But it always says 0. I ran in parallel an equivalent line of code in Bash, which shows that the file was indeed changing during this time:

$ f=/sys/class/net/wlan0/statistics/rx_bytes; while true; do a=`cat $f`; sleep 1; echo $((`cat $f`-a)); done 98 98 2132 3178 230 306 98 98 729

Why does Haskell not see it changing?

最满意答案

readFile是懒惰的,也就是说,除非你计算绑定的变量,否则它实际上并不访问文件中的数据:在你的情况下, read a 。 此时线程延迟已经通过,并且您评估的文件处于与b相同的状态!

这样做:

forever $ do a <- fmap read $ readFile f a `seq` threadDelay (10^6) b <- fmap read $ readFile f print $ b - a

readFile is lazy, i.e. it doesn't actually access the data in the file until you evaluate the variable bound to it: in your case, read a. At which time the thread delay has already passed, and you evaluate the file in the same state as b!

Do it this way:

forever $ do a <- fmap read $ readFile f a `seq` threadDelay (10^6) b <- fmap read $ readFile f print $ b - a

更多推荐

本文发布于:2023-07-30 06:48:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:每隔   文件   两秒读   reading   giving

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!