You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Boost Beast同步应用:多线程调用ws.write需显式处理并发吗?

多线程并发调用Boost Beast ws.write是否需要显式并发处理?

参考Boost Beast官方WebSocket同步服务器示例,核心循环代码如下:

for(;;)
{
    // 存储传入消息的缓冲区
    beast::flat_buffer buffer;

    // 读取消息
    ws.read(buffer);

    // 回显消息
    ws.text(ws.got_text());
    ws.write(buffer.data());
}

我将场景简化为仅循环调用自定义mywrite函数(内部调用ws.write写入不同数据),单线程顺序调用完全正常。现在有个疑问:如果多线程并发调用mywrite(也就是并发调用ws.write),是否需要用strand或mutex这类显式并发处理机制?

查阅Boost Beast文档中关于websocket::stream的线程安全说明:

Thread Safety

Distinct objects: Safe.

Shared objects: Unsafe. The application must also ensure that all asynchronous operations are performed within the same implicit or explicit strand.

文档同时提到,单线程或同步应用可以直接实例化websocket::stream<tcp_stream> ws(ioc),无需显式strand。这似乎暗示ws对象本身非线程安全,但同步单线程场景下不需要额外处理?

我之前没接触过asio,自己做了多线程测试没发现问题,但没法保证这种情况的通用性,也不确定测试是否有效。测试代码如下:

auto lt = [&](unsigned long long i)
{
    char s[1000] = {0};
    for(;;++i)
    {
        sprintf(s, "Hello from thread:%llu", i);
        mywrite(s,30);
    }
};

std::thread(lt, 10000000u).detach();
std::thread(lt, 20000000u).detach();
std::thread(lt, 30000000u).detach();

// 按照官方示例初始化ws client

for (int i = 0; i < 100; ++i)
{
    beast::flat_buffer buffer;
    // 将消息读取到缓冲区
    ws.read(buffer);
    
    // make_printable 函数用于打印 ConstBufferSequence
    std::cout << beast::make_printable(buffer.data()) << std::endl;
}

现明确提问:多线程并发调用Boost Beast的ws.write时,是否需要显式处理并发?


内容的提问来源于stack exchange,提问作者ArthurChamz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:06:51