2012-04-23 4 views
0

코드가 here 인 Blocking Queue를 사용하여 리더/라이터 문제를 구현하려고 시도했습니다. 전체가 컴파일되어 실행되지만 reader() 및 writer() 함수에서 비동기 {...} 부분은 출력을 전혀 생성하지 않습니다. 비록 내가 F #을 가진 멍청이이기는하지만이 코드를 가진 튜토리얼 페이지가 진짜처럼 보였기 때문에 나는 그들이 제대로 호출되고 있다고 확신한다. - async 실행하기 전에 프로그램이 바로 종료됩니다F #을 사용하는 비동기 함수에서 출력이 없습니까?

open System 
open System.IO 
open System.Collections.Generic 
//open System.Runtime.Serialization.Formatters.Binary 

///defining Agent 
type Agent<'T> = MailboxProcessor<'T> 

///defining Message 
type internal BlockingAgentMessage<'T> = 
    | Get of AsyncReplyChannel<'T> 
    | Add of 'T * AsyncReplyChannel<unit> 

/// Agent-based implementation of producer/consumer problem 
type BlockingQueueAgent<'T>(maxLength) = 
    let agent = Agent.Start(fun agent -> 
     let queue = new Queue<_>() 
     //let queue = new Queue() 
     // State machine running inside the agent 
     let rec emptyQueue() = 
      agent.Scan(fun msg -> 
       match msg with 
       | Add(value, reply) -> Some(enqueueAndContinue(value, reply)) 
       | _ -> None) 
     and fullQueue() = 
      agent.Scan(fun msg -> 
       match msg with 
       | Get(reply) -> Some(dequeueAndContinue(reply)) 
       | _ -> None) 
     and runningQueue() = async { 
      let! msg = agent.Receive() 
      match msg with 
      | Add(value, reply) -> return! enqueueAndContinue(value, reply) 
      | Get(reply) -> return! dequeueAndContinue(reply) } 
     and enqueueAndContinue (value, reply) = async { 
      queue.Enqueue(value) 
      reply.Reply() 
      return! chooseState() } 
     and dequeueAndContinue (reply) = async { 
      reply.Reply(queue.Dequeue()) 
      return! chooseState() } 
     and chooseState() = 
      if queue.Count = 0 then emptyQueue() 
      elif queue.Count = maxLength then fullQueue() 
      else runningQueue() 

     // Start with an empty queue 
     emptyQueue()) 

    /// Asynchronously adds item to the queue. If the queue 
    /// is full, it blocks until some items are removed. 
    member x.AsyncAdd(v:'T) = 
     agent.PostAndAsyncReply(fun ch -> Add(v, ch)) 

    /// Asynchronously gets item from the queue. If the queue 
    /// is empty, it blocks until some items are added. 
    member x.AsyncGet() = 
     agent.PostAndAsyncReply(Get) 




let ag = new BlockingQueueAgent<int>(3) 
printfn "Blocking Queue Agent program" 

let writer() = async { 

    for i in 0 .. 10 do 
     do! ag.AsyncAdd(i) 
     printfn "Added: %d" i } 

let reader() = async { 
    while true do 
     let! v = ag.AsyncGet() 
     do! Async.Sleep(1000) 
     printfn "Got: %d" v } 

reader() |> Async.Start 
printfn "Started Reader ..." 
writer() |> Async.Start 
printfn "Started Writer ..." 

답변

5

코드가 괜찮 :

여기에 전체 코드입니다.

System.Console.Read() |> ignore 

과 같이 추가하십시오. 이것은 나를 위해 작동

+0

아 좋은 getch() C처럼! f #에있는 멍청한 녀석은 확실히 단점을 가지고있다. 감사. – AruniRC

관련 문제