使用C或C++可以实现异步编程吗?

Pro*_*uce 1 c c++

Javascript有助于异步编程.使用回调而不是uniflow的异步编程,可能与C?(或C++)

PS:很明显C#5.0已经实现了它.

编辑:

在C和C++中类似于nodejs的框架是什么?

编辑2:异步编程有助于扩展用户而无需多线程(这对大型用户应用程序很重要)为什么基于回调的异步方法可用于常规应用程序(只有100个用户)?

Jiw*_*wan 7

您可能需要操作线程,函数指针,仿函数,lambdas,或者您可以使用专用库.好吧,一切都可以用C++完成.

在您的评论中,您正在谈论NodeJS.我想你想要的是一个用于文件,网络的异步库......在这种情况下,您可以看看Boost.Asio在C++中使用异步编程的难易程度.

这是一个简单的例子,部分来自他们的文档:

class server
{
public:
  server(boost::asio::io_service& io_service,
      const tcp::endpoint& endpoint)
    : acceptor_(io_service, endpoint)
  {
    do_accept();
  }

private:
  void do_accept()
  {
    acceptor_.async_accept(socket_,
        [this](boost::system::error_code ec)
        {
          if (!ec)
          {
            // Do your stuff here with the client socket when one arrive.
          }

          do_accept(); // Start another async call for another client.
        });
   // Your server can do some other stuff here without waiting for a client.
  }

  tcp::acceptor acceptor_;
};
Run Code Online (Sandbox Code Playgroud)

这是一个异步接受某些客户端的基本服务器.该函数tcp::acceptor::asyn_accept将返回imediatly并在客户端连接时稍后调用回调.在我们的例子中,这个回调是一个lambda函数; 来自的新功能C++11.