C ++等待但允许事件触发

时间:2015-11-05 22:39:01

标签: c++ c++11 winapi signalr concurrency-runtime

使用Visual Studio 2013构建SignalR C ++客户端,我从NuGet Package Microsoft.AspNet.SignalR.Client.Cpp.v120.WinDesktop 的工作示例代码开始,源{{3} }

在查看库源时,我觉得事件处理过程基于here(pplx :: task),它依赖于Concurrency Runtime

void chat(const utility::string_t& name)
{
    signalr::hub_connection connection{ U("https://testsite") };
    auto proxy = connection.create_hub_proxy(U("ChatHub"));
    proxy.on(U("broadcastMessage"), [](const web::json::value& m)
    {
        ucout << std::endl << m.at(0).as_string() << U(" wrote:") << m.at(1).as_string() << std::endl << U("Enter your message: ");
    });

    connection.start()
        .then([proxy, name]()
    {
        for (;;)
        {
            utility::string_t message;
            std::getline(ucin, message);

            if (message == U(":q"))
            {
                break;
            }

            send_message(proxy, name, message);
        }
    })
        .then([&connection]() // fine to capture by reference - we are blocking so it is guaranteed to be valid
    {
        return connection.stop();
    })
        .then([](pplx::task<void> stop_task)
    {
        try
        {
            stop_task.get();
            ucout << U("connection stopped successfully") << std::endl;
        }
        catch (const std::exception &e)
        {
            ucout << U("exception when starting or stopping connection: ") << e.what() << std::endl;
        }
    }).get();
}

我想要消除&#34;用户输入&#34;零件;而当一个特定的&#34; broadcastMessage&#34;已被收到。

如果我用sleep语句替换for循环,则broadcastMessage事件将停止触发。

如果我在没有getline的情况下使用for循环,完成后将bComplete设置为true,它会按照我想要的方式工作,但会导致高CPU使用率(显然)

for (;;)
{
if (bComplete) break;
}

理想情况下,我希望连接启动,然后等到broadcastMessage事件发出信号以关闭连接。 另外&#34;聊天&#34;函数不应该返回,直到连接关闭。

2 个答案:

答案 0 :(得分:3)

我可以在your answer中看到您已经发现Windows event objects;但是,如果您正在寻找独立于C ++ 11平台的解决方案,请考虑std::condition_variable

unsigned int accountAmount;
std::mutex mx;
std::condition_variable cv;

void depositMoney()
{
    // go to the bank etc...
    // wait in line...
    {
        std::unique_lock<std::mutex> lock(mx);
        std::cout << "Depositing money" << std::endl;
        accountAmount += 5000;
    }
    // Notify others we're finished
    cv.notify_all();
}
void withdrawMoney()
{
    std::unique_lock<std::mutex> lock(mx);
    // Wait until we know the money is there
    cv.wait(lock);
    std::cout << "Withdrawing money" << std::endl;
    accountAmount -= 2000;
}
int main()
{
    accountAmount = 0;
    std::thread deposit(&depositMoney);
    std::thread withdraw(&withdrawMoney);
    deposit.join();
    withdraw.join();
    std::cout << "All transactions processed. Final amount: " << accountAmount << std::endl;
    return 0;
}

在这个例子中,我们制作了两个主题:一个是将钱存入账户,另一个是取款。因为线程有可能首先撤回资金,特别是因为depositMoney()涉及更多处理,我们需要等到我们知道钱存在。我们在访问钱之前锁定了我们的线程,然后告诉condition_variable我们在等什么。 condition_variable将解锁该帖子,一旦存入资金并调用notify_all(),我们就会被重新唤醒以完成处理我们的逻辑。

请注意,使用Windows event objects可以完全相同。您使用std::condition_variable::wait()std::condition_variable::notify_all()代替SetEvent()WaitForSingleObject(),而不是.logo{ vertical-align: middle; display: inline-block; margin-top: .5em } chatMenuView。这与平台无关。

答案 1 :(得分:0)

我使用WinAPI WaitForSingleObject:

HANDLE hEvent;
    void chat(const utility::string_t& name)
    {
        signalr::hub_connection connection{ U("https://testsite") };
        auto proxy = connection.create_hub_proxy(U("ChatHub"));
        proxy.on(U("broadcastMessage"), [](const web::json::value& m)
        {
            ucout << std::endl << m.at(0).as_string() << U(" wrote:") << m.at(1).as_string() << std::endl;
        if (m.at(1).as_string() == L"quit")
            {
                SetEvent(hEvent);
            }
        });

    hEvent = CreateEvent(0, TRUE, FALSE, 0);

        connection.start()
            .then([proxy, name]()
        {
            WaitForSingleObject(hEvent, INFINITE);
        })
            .then([&connection]() // fine to capture by reference - we are blocking so it is guaranteed to be valid
        {
            return connection.stop();
        })
            .then([](pplx::task<void> stop_task)
        {
            try
            {
                stop_task.get();
                ucout << U("connection stopped successfully") << std::endl;
            }
            catch (const std::exception &e)
            {
                ucout << U("exception when starting or stopping connection: ") << e.what() << std::endl;
            }`enter code here`
        }).get();
    }