Skip to content

how to make the Async code non blocking? #342

@michelson

Description

@michelson

Sorry for the noob question here, but something that I do not understand is that Async is blocking the code execution; I'm assuming that Async should not block and run concurrently, but I am not sure if I understand this correctly.

Example 1, a running server:

require 'async/io'
      require 'async/io/unix_endpoint'

      @server = Async::IO::Endpoint.unix("./tmp.sock")
  
      # This async blocks the execution as the server runs forever:
        Async do |task|
          @server.accept do |client|
            Console.logger.info(client, "Accepted connection")
            a = client.read(6)
            sleep 1
            client.send "elloh\n"
            client.close_write
          end
        end

      sleep 3

      10.times do
        UNIXSocket.open("./tmp.sock") do |socket|
          socket << "hello\n"
          p socket.read(6)
          socket.close
        end
      end

now, If I put a Thread new on the Async, it will not block.

require 'async/io'
      require 'async/io/unix_endpoint'

      @server = Async::IO::Endpoint.unix("./tmp.sock")

      Thread.new do 
        Async do |task|
          @server.accept do |client|
            Console.logger.info(client, "Accepted connection")
            a = client.read(6)
            sleep 1
            client.send "elloh\n"
            client.close_write
          end
        end
      end

      sleep 3

      10.times do
        UNIXSocket.open("./tmp.sock") do |socket|
          socket << "hello\n"
          p socket.read(6)
          socket.close
        end
      end

how can I achieve the non block only with async gems?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions