- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 UDP 服务器,它反射(reflect)它收到的每个 ping 消息(我认为这很有效)。我是客户端,然后我想做两件事:
forkIO
事情,我下面的客户端代码过早结束/根本不做任何计数。
tryOnePing
返回 Int 4 的 250 倍。为什么会这样?
main = withSocketsDo $ do
s <- socket AF_INET Datagram defaultProtocol
hostAddr <- inet_addr host
thread <- forkIO $ receiveMessages s
-- is there any better way to eg to run that in parallel and make sure
-- that sending/receiving are asynchronous?
-- forM_ [0 .. 10000] $ \i -> do
-- sendTo s "ping" (SockAddrInet port hostAddr)
-- actually this would be preferred since I can discard the Int 4 that
-- it returns but forM or forM_ are out of scope here?
let tryOnePing i = sendTo s "ping" (SockAddrInet port hostAddr)
pings <- mapM tryOnePing [0 .. 1000]
let c = length $ filter (\x -> x==4) pings
-- killThread thread
-- took that out to make sure the function receiveMessages does not
-- end prematurely. still seems that it does
sClose s
print c
-- return()
receiveMessages :: Socket -> IO ()
receiveMessages socket = forever $ do
-- also tried here forM etc. instead of forever but no joy
let recOnePing i = recv socket 1024
msg <- mapM recOnePing [0 .. 1000]
let r = length $ filter (\x -> x=="PING") msg
print r
print "END"
最佳答案
这里的主要问题是当您的主线程完成时,所有其他线程都会自动终止。你必须让主线程等待 receiveMessages thread
,或者它很可能会在收到任何响应之前简单地完成。一种简单的方法是使用 MVar
.
安 MVar
是一个同步单元格,可以是空的,也可以只保存一个值。如果当前线程试图从空 MVar
中获取数据,它将被阻塞或插入一个完整的。
在这种情况下,我们不关心值本身,所以我们只存储一个 ()
在里面。
我们将从 MVar
开始空的。然后主线程将 fork 接收者线程,发送所有数据包,并尝试从 MVar
中获取值。 .
import Control.Concurrent.MVar
main = withSocketsDo $ do
-- prepare socket, same as before
done <- newEmptyMVar
-- we need to pass the MVar to the receiver thread so that
-- it can use it to signal us when it's done
forkIO $ receiveMessages sock done
-- send pings, same as before
takeMVar done -- blocks until receiver thread is done
()
在
MVar
表示我们已完成接收。
receiveMessages socket done = do
-- receive messages, same as before
putMVar done () -- allows the main thread to be unblocked
sendTo
不保证会发送整个字符串。您必须检查返回值以查看发送了多少,如果不是全部发送,则重试。即使是像 "ping"
这样的短消息也可能发生这种情况。如果发送缓冲区已满。 recv
需要一个连接的套接字。你会想要使用 recvFrom
反而。 (尽管由于某种未知原因它仍然可以在我的 PC 上运行)。 MVar
将用于传达接收到的数据包的数量,而不仅仅是 ()
.这样,您就可以完成主线程的所有输出。或者,使用另一个 MVar
作为互斥锁来控制对标准输出的访问。 关于networking - 为什么我的并发 Haskell 程序过早终止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8272241/
我的测试代码: int SIZE = 1900; int[][] array = new int[SIZE][]; for (int i = 0; i < SIZE; i++) { array[i
我有一堆 WAV 文件和一个将它们复制到另一个目录的脚本,但使用 SoX 处理了一些文件。输出的文件都应该有 1 个 channel ,采样率不超过 44.1khz。我的大多数文件要么有一个以上的 c
我正在运行一个相当占用内存的 Python 脚本,但似乎我的机器正在提前终止进程。我安装了 16GB(并通过 lshw -class memory 确认),但我的进程似乎在使用量达到 4GB 左右时被
我很难确定在使用 .NET 的 HttpWebRequest 类调用远程服务器(特别是 REST Web 服务)时是否有办法处理潜在的连接问题。根据我的调查,WebClient 类的行为是相同的,这在
所以我有这个网址: http://test.com/afolder/who-else-wants-to-make-horror-movies%3f/ 这是 URL 编码版本: http://test.
我是一名优秀的程序员,十分优秀!