Edw*_*ard 6 c++ multithreading tcp boost-asio c++14
当使用两个线程发送和接收时,如何避免数据竞争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
Run Code Online (Sandbox Code Playgroud)
要测试,我使用以下命令运行服务器:
valgrind --tool=helgrind --log-file=helgrind.txt ./concurrent
Run Code Online (Sandbox Code Playgroud)
然后我telnet 127.0.0.1 5555在另一个窗口中使用来创建与服务器的连接.什么helgrind正确地指出的是,有一个数据竞争,因为两者runTx并runRx试图以异步方式访问相同的数据流:
== 16188 ==线程#1在0x1FFEFFF1CC读取大小1期间可能发生数据竞争
== 16188 ==持有的锁:无
...更多的线路被省略了
#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";
}
}
}
Run Code Online (Sandbox Code Playgroud)
是的,您正在共享流下的套接字,但没有同步
旁注,与布尔标志相同,可以通过更改轻松“修复”:
Run Code Online (Sandbox Code Playgroud)std::atomic_bool want_quit; std::atomic_bool want_reset;
说实话,我认为没有什么好的解决办法。您自己说过:操作是异步的,因此如果您尝试同步执行它们,就会遇到麻烦。
你可以尝试想想黑客。如果我们基于相同的底层套接字(文件描述符)创建一个单独的流对象会怎么样?这不会很容易,因为这样的流不是 Asio 的一部分。
但我们可以使用 Boost Iostreams 来破解:
#define BOOST_IOSTREAMS_USE_DEPRECATED
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
// .... later:
// HACK: procure a _separate `ostream` to prevent the race, using the same fd
namespace bio = boost::iostreams;
bio::file_descriptor_sink fds(stream.rdbuf()->native_handle(), false); // close_on_exit flag is deprecated
bio::stream<bio::file_descriptor_sink> hack_ostream(fds);
con.run(stream, hack_ostream);
Run Code Online (Sandbox Code Playgroud)
事实上,这在没有竞争的情况下运行(在同一个套接字上同时读取和写入是可以的,只要您不共享包装它们的非线程安全 Asio 对象)。
不要那样做。这是一个拼凑。您使事情变得复杂,显然是为了避免使用异步代码。我会咬紧牙关。
将 IO 机制从服务逻辑中分离出来并不需要太多工作。您最终将摆脱随机限制(您可以考虑处理多个客户端,您可以根本不使用任何线程等)。
如果您想了解一些中间立场,请查看 stackful coroutines ( http://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/spawn.html )
仅供参考
请注意,我进行了重构以消除对指针的需要。您不会转让所有权,因此参考即可。如果您不知道如何将引用传递给
bind/std::thread构造函数,技巧就在std::ref您将看到的。[对于压力测试,我大大减少了延迟。]
#include <boost/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);
std::atomic_bool want_quit;
std::atomic_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(1));
out.flush();
}
return 0;
}
int Console::run(std::istream &in, std::ostream &out) {
want_reset = false;
std::thread t1{&Console::runRx, this, std::ref(out)};
int status = runTx(in);
t1.join();
return status;
}
#define BOOST_IOSTREAMS_USE_DEPRECATED
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
int main()
{
Console con;
boost::asio::io_service ios;
// IPv4 address, port 5555
boost::asio::ip::tcp::acceptor acceptor(ios, boost::asio::ip::tcp::endpoint{boost::asio::ip::tcp::v4(), 5555});
while (!con.getQuitValue()) {
boost::asio::ip::tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
{
// HACK: procure a _separate `ostream` to prevent the race, using the same fd
namespace bio = boost::iostreams;
bio::file_descriptor_sink fds(stream.rdbuf()->native_handle(), false); // close_on_exit flag is deprecated
bio::stream<bio::file_descriptor_sink> hack_ostream(fds);
con.run(stream, hack_ostream);
}
if (con.wantReset()) {
std::cout << "resetting\n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
测试:
netcat localhost 5555 <<<quit
This is message number 0
This is message number 1
This is message number 2
Run Code Online (Sandbox Code Playgroud)
和
commands=( one two one two one two one two one two one two one two three )
while sleep 0.1; do echo ${commands[$(($RANDOM%${#commands}))]}; done | (while netcat localhost 5555; do sleep 1; done)
Run Code Online (Sandbox Code Playgroud)
无限期地运行,偶尔会重置连接(当命令“三”已发送时)。
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |