【发布时间】:2018-06-15 11:53:42
【问题描述】:
我的问题
使用两个线程通过asio::ip::tcp::iostream 发送和接收时如何避免数据竞争?
设计
我正在编写一个使用asio::ip::tcp::iostream 进行输入和输出的程序。该程序通过端口 5555 接受来自(远程)用户的命令,并通过同一 TCP 连接向用户发送消息。因为这些事件(从用户接收的命令或发送给用户的消息)是异步发生的,所以我有单独的发送和接收线程。
在这个玩具版本中,命令是“一”、“二”和“退出”。当然“退出”退出程序。其他命令什么都不做,任何无法识别的命令都会导致服务器关闭 TCP 连接。
传输的消息是简单的序列号消息,每秒发送一次。
在这个玩具版本和我正在尝试编写的真实代码中,传输和接收进程都使用阻塞 IO,因此似乎没有使用std::mutex 或其他同步的好方法机制。 (在我的尝试中,一个进程会抓取互斥体然后阻塞,这对这个不起作用。)
构建和测试
为了构建和测试它,我在 64 位 Linux 机器上使用 gcc 版本 7.2.1 和 valgrind 3.13。构建:
g++ -DASIO_STANDALONE -Wall -Wextra -pedantic -std=c++14 concurrent.cpp -o concurrent -lpthread
为了测试,我使用以下命令运行服务器:
valgrind --tool=helgrind --log-file=helgrind.txt ./concurrent
然后我在另一个窗口中使用telnet 127.0.0.1 5555 来创建到服务器的连接。 helgrind 正确指出的是存在数据竞争,因为 runTx 和 runRx 都试图异步访问同一个流:
==16188== 线程 #1 在 0x1FFEFFF1CC 读取大小 1 期间可能存在数据竞争
==16188== 持有锁:无
...省略了更多行
并发.cpp
#include <asio.hpp>
#include <iostream>
#include <fstream>
#include <thread>
#include <array>
#include <chrono>
class Console {
public:
Console() :
want_quit{false},
want_reset{false}
{}
bool getQuitValue() const { return want_quit; }
int run(std::istream *in, std::ostream *out);
bool wantReset() const { return want_reset; }
private:
int runTx(std::istream *in);
int runRx(std::ostream *out);
bool want_quit;
bool want_reset;
};
int Console::runTx(std::istream *in) {
static const std::array<std::string, 3> cmds{
"quit", "one", "two",
};
std::string command;
while (!want_quit && !want_reset && *in >> command) {
if (command == cmds.front()) {
want_quit = true;
}
if (std::find(cmds.cbegin(), cmds.cend(), command) == cmds.cend()) {
want_reset = true;
std::cout << "unknown command [" << command << "]\n";
} else {
std::cout << command << '\n';
}
}
return 0;
}
int Console::runRx(std::ostream *out) {
for (int i=0; !(want_reset || want_quit); ++i) {
(*out) << "This is message number " << i << '\n';
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
out->flush();
}
return 0;
}
int Console::run(std::istream *in, std::ostream *out) {
want_reset = false;
std::thread t1{&Console::runRx, this, out};
int status = runTx(in);
t1.join();
return status;
}
int main()
{
Console con;
asio::io_service ios;
// IPv4 address, port 5555
asio::ip::tcp::acceptor acceptor(ios,
asio::ip::tcp::endpoint{asio::ip::tcp::v4(), 5555});
while (!con.getQuitValue()) {
asio::ip::tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
con.run(&stream, &stream);
if (con.wantReset()) {
std::cout << "resetting\n";
}
}
}
【问题讨论】:
-
这将是一个Producer - Consumer pattern。有几种不同的解决方案可用,其中一些没有明确使用信号量等。
标签: c++ multithreading tcp c++14 boost-asio