【发布时间】:2019-11-23 13:38:21
【问题描述】:
TL;DR
我需要一段代码来正确执行多线程并且不返回或崩溃。我需要做些什么来消耗任何 return 或 try/catch 块以使 main() 不会结束?
故事
我在 Google protobufs 中使用 cpp 已经有一段时间了,但我遇到了一个我尝试解决方案无法解决的问题。我开始使用 google protobufs 和 cpp 从 this link 学习服务器-客户端套接字程序。我首先通过编辑.proto 文件将.proto 文件转换为proto3。然后我能够创建一个 CMake 文件来编译程序。
我的问题
我需要制作一个新的客户端程序,这样,当server.cpp 被Ctrl+c 取消时,客户端程序会NOT 崩溃、退出、seg 错误等。基本上,当服务器死了,客户端应该等到服务器重新上线。
我尝试了什么?
我尝试了两件事:
- 我将整个套接字创建(包括变量创建)放入一个巨大的 while 循环中。然后我在开始时有一个延迟,如果无法建立连接,程序会等待然后重试。
- 多线程与
boost
我尝试使用boost::thread 和boost::future 创建boost::async。我在main() 中有一个循环,它将创建一个boost::async() 对象的向量(长度为1),程序的整个其余部分在传递给boost::async() 构造函数的方法中调用。然后我用begin()和end()简单地调用了迭代器上的boost::wait_for_all()。 This is where我有了期货的想法。下面是一个语法示例:
while (true)
{
printingmutex.lock();
cout << "------------------\nStarting initialization of socket.\n" << endl;
printingmutex.unlock();
// Now I create the threads.
std::vector<boost::future<void>> futures;
futures.push_back(boost::async([host_name]{ doSocketswag(host_name); }));
boost::wait_for_all(futures.begin(), futures.end());
// Delay function after disconnection, implementation irrelevant to the question
sleepApp(2000); // 2 seconds
}
为简洁起见,这里是新的.proto 文件,用于转换为proto3:
syntax = "proto3";
message log_packet {
fixed64 log_time = 1;
fixed32 log_micro_sec = 2;
fixed32 sequence_no = 3;
fixed32 shm_app_id = 4;
string packet_id = 5;
string log_level= 6;
string log_msg= 7;
}
为什么这很重要?
这很重要,因为当我解决了这个问题后,我会将客户端程序移植到我的 Ubuntu 机器以外的其他平台,但我仍将使用我的 Ubuntu 机器,并且我需要能够运行程序在发送消息之外运行。我还可以将GUI 添加到程序中,因此我需要能够将套接字线程与程序的其余部分分开,从而防止不良连接杀死客户端程序。
总结
如何让客户端程序多线程,这样套接字通信就不会了
- 杀死程序
- 通过
main()返回 - 只杀掉socket线程,不杀别的?
一个基本的、简洁的实现显示套接字独立于主程序运行就足够了。
另外,为了加快响应速度,我有一个 CMake 文件来编译 client 和 server 和 .proto 文件。我分享它是为了让你们可以花更多的时间在实际回答问题上,而不是花时间在编译代码上。
# Compiling the program, assuming all of the source files are in the same directory:
# mkdir build
# cd build
# cmake ..
# cmake --build . -- -j8 -l8
set(PROJECT_NAME CppProtobufdemo)
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
project(${PROJECT_NAME} LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
add_definitions(-std=c++11)
# CMAKE_CURRENT_SOURCE_DIR - This is the directory where CMake is running.
set(CMAKE_BINARY_DIR ${CMAKE_SOURCE_DIR}/build)
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR})
set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib)
find_package( Boost REQUIRED system thread timer chrono)
if(Boost_FOUND)
message("Boost was found.")
message(${Boost_INCLUDE_DIR})
endif()
include_directories(${CMAKE_CURRENT_BINARY_DIR})
set(THE_USER $ENV{USER})
message("This is the com user_:" ${THE_USER})
set(PROGRAMS_TO_COMPILE
server
client
)
# These lines are for autogenerating code from the *.proto files with CMake.
find_package(Protobuf REQUIRED)
if(PROTOBUF_FOUND)
message("Google Protobuf has been found.")
endif()
include_directories(${Protobuf_INCLUDE_DIRS})
include_directories(${CMAKE_CURRENT_BINARY_DIR})
# https://cmake.org/cmake/help/git-master/module/FindProtobuf.html
protobuf_generate_cpp(PROTO_SRCS PROTO_HDRS message.proto)
# I want to see if I can access these proto files from python scripts
protobuf_generate_python(PROTO_PY message.proto)
foreach(aprogram ${PROGRAMS_TO_COMPILE})
add_executable(${aprogram} ${PROTO_SRCS} ${PROTO_HDRS} ${PROJECT_SOURCE_DIR}/${aprogram}.cpp )
target_link_libraries(${aprogram} ${Boost_LIBRARIES})
target_link_libraries(${aprogram} ${PROTOBUF_LIBRARIES})
endforeach()
另一件事:我一直在处理过程中摆脱goto FINISH 语句。
如果您有任何问题或后续问题,我很乐意回复。
编辑:
我已经尝试过换行
boost::wait_for_all(futures.begin(), futures.end());
在这样的尝试中:
try {
// Now that I have created all of the threads, I need to wait for them to finish.
boost::wait_for_all(futures.begin(), futures.end());
}
catch (const std::exception& e)
{
// Just keep swimming
cout << "Thread died" << endl;
}
现在错误消息不会被推送。相反,程序只是退出,没有任何错误或任何消息。
我正在使用return 语句来终止线程方法,但它们不应该终止main() 线程-除非我还缺少其他东西。这是我用来演示此“修复”的客户端代码:
// This is for the futures functionality
#define BOOST_THREAD_VERSION 4
//
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
// cmake --build . -- -j8 -l8
#include "message.pb.h"
#include <iostream>
#include <google/protobuf/message.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl_lite.h>
//
#include <boost/thread.hpp>
#include <chrono>
#include <thread>
using namespace google::protobuf::io;
using namespace std;
void doSocketSwag(void);
void sleepApp(int millis)
{
std::this_thread::sleep_for(std::chrono::milliseconds{millis});
}
// Boost sleep function
void wait(int milliseconds)
{
boost::this_thread::sleep_for(boost::chrono::milliseconds{milliseconds});
}
int main(int argv, char** argc)
{
// I will put this whole thing into a while loop
while (true)
{
cout << "Creating threads." << endl;
std::vector<boost::future<void>> futures;
// The socket thread
futures.push_back(boost::async([]{ doSocketSwag(); }));
// Now I need to catch exceptions
try {
// Now that I have created all of the threads, I need to wait for them to finish.
boost::wait_for_all(futures.begin(), futures.end());
}
catch (const std::exception& e)
{
// Just keep swimming
cout << "Thread died" << endl;
}
}
//delete pkt;
//FINISH:
//close(hsock);
return 0;
}
//
void doSocketSwag(void)
{
log_packet payload;
payload.set_log_time(10);
payload.set_log_micro_sec(10);
payload.set_sequence_no(1);
payload.set_shm_app_id(101);
payload.set_packet_id("TST");
payload.set_log_level("DEBUG");
payload.set_log_msg("What shall we say then");
//cout<<"size after serilizing is "<<payload.ByteSize()<<endl;
int siz = payload.ByteSize()+4;
char *pkt = new char [siz];
google::protobuf::io::ArrayOutputStream aos(pkt,siz);
CodedOutputStream *coded_output = new CodedOutputStream(&aos);
coded_output->WriteVarint32(payload.ByteSize());
payload.SerializeToCodedStream(coded_output);
int host_port= 1101;
char* host_name="127.0.0.1";
struct sockaddr_in my_addr;
char buffer[1024];
int bytecount;
int buffer_len=0;
int hsock;
int * p_int;
int err;
hsock = socket(AF_INET, SOCK_STREAM, 0);
if(hsock == -1){
printf("Error initializing socket %d\n",errno);
//goto FINISH;
return;
}
p_int = (int*)malloc(sizeof(int));
*p_int = 1;
if( (setsockopt(hsock, SOL_SOCKET, SO_REUSEADDR, (char*)p_int, sizeof(int)) == -1 ) || (setsockopt(hsock, SOL_SOCKET, SO_KEEPALIVE, (char*)p_int, sizeof(int)) == -1 ) ){
printf("Error setting options %d\n",errno);
free(p_int);
//goto FINISH;
return;
}
free(p_int);
my_addr.sin_family = AF_INET ;
my_addr.sin_port = htons(host_port);
memset(&(my_addr.sin_zero), 0, 8);
my_addr.sin_addr.s_addr = inet_addr(host_name);
if( connect( hsock, (struct sockaddr*)&my_addr, sizeof(my_addr)) == -1 ){
if((err = errno) != EINPROGRESS){
fprintf(stderr, "Error connecting socket %d\n", errno);
//goto FINISH;
return;
}
}
while (true)
{
if( (bytecount=send(hsock, (void *) pkt,siz,0))== -1 ) {
// THIS is where the program dies.
fprintf(stderr, "Error sending data %d\n", errno);
//goto FINISH;
break;
}
//printf("Sent bytes %d\n", bytecount);
//usleep(1);
sleepApp(1000);
cout << "Thread slept for 1 second." << endl;
}
}
如果return 语句很糟糕,我该如何替换它们?
【问题讨论】:
-
我不清楚如果服务器离线,为什么客户端会崩溃?如果套接字死了,
doSocketswag会抛出吗?如果是这样,你不能抓住它吗? -
客户端在这个代码块中:
if( (bytecount=send(hsock, (void *) pkt,siz,0))== -1 ) { fprintf(stderr, "Error sending data %d\n", errno); goto FINISH; },它告诉我它出错了,给了我一个错误号,然后退出程序。我还应该说上面粘贴的代码块处于 while(true) 循环中,但这不会改变一般逻辑。此外,在我的个人代码中,我还有很多其他逻辑在进行,但上面链接的原始 SO 帖子为概念证明提供了相同的想法。我还应该提到我在原始程序中摆脱了goto FINISH。 -
我知道代码失败的哪里。我不知道该怎么做来修复它。调试器不会帮助我弄清楚 what 用@MaxVollmer 替换 代码。
-
也许我太累了,但即使在重新阅读您的问题后,我也看不到任何有关代码失败位置的信息。你能添加它或让它更清楚吗?
-
可能是以上所有的组合......我也去过那里。
标签: c++ multithreading sockets boost protocol-buffers