Killing forked threads
When we create a new thread, we can keep track of its corresponding thread ID to kill it later manually.
In this recipe, we will be creating a command-line interface for forking new processes to download a huge file. A download will be initiated with the d
command followed by a number. So, running d 1
will launch a thread to download item #1.
We will learn how to kill threads while they are still running. Our command to kill threads will look like k 1
in order to kill the downloaded item #1.
How to do it…
In a new file, which we call Main.hs
, insert the following code:
- Import the required packages as follows:
import Control.Concurrent import qualified Data.Map as M
- Let
main
call the helperdownload
function:main = download (M.empty :: M.Map Int [ThreadId])
- Define a function to take the user queries and appropriately respond as follows:
download m = do input <- (getLine >>= return . words) respond m input >>= download
- Respond to a download request:
respond...