c++ - 线程不刷新数据,在屏幕上显示数据时出错

标签 c++ multithreading file sockets

我正在创建一个套接字程序来将数据从一台电脑传输到另一台电脑,但是当我将一些二进制数据发送到另一端进行处理时我遇到了问题。 在这种情况下,我需要一个线程来监听消息套接字,同时数据套接字发送数据。 所以我发现问题不在于套接字,如果我尝试将数据写入屏幕(这次没有套接字),就会出现问题。 所以我尝试使用 fflush(stdout) 刷新数据,但没有成功。 这些代码以这种方式工作。

Initialize the 2 sockets.
Initialize 2 threads.
  One to get the data back through the data socket.
  The other send the data.    
And while sending all the data one while(true){sleep(1)} in the main function, because the data can take 1 second to be processed or one hour so i keep the program alive this way (Don't know if that is the better way).

我创建了一个较小的版本,仅使用一个线程来读取和发送到屏幕,同时在主线程中。

代码:

#include <iostream>
#include <fstream>
#include <string.h>

using namespace std;

const int RCVBUFSIZE=2000;
char echoString[RCVBUFSIZE];

static void * _sendExec(void *instance);

int main(){
  pthread_t m_thread;
  int merror;
  merror=pthread_create(&m_thread, NULL, _sendExec, NULL);
  while(1){sleep(1);}
}
static void * _sendExec(void *instance){
  int size;
  for(;;){
    while((size=read(fileno(stdin), echoString, RCVBUFSIZE))>0) write(fileno(stdout), echoString, size);
    fflush(stdin);
    fflush(stdout);
    pthread_exit(0);
  }
}

如果你试试 cat file.tar.gz | ./a.out | tar -zvt 你可以看到并不是所有的数据都显示在屏幕上,如果我把它放在主屏幕上,删除 sleep 就可以了,问题是我需要数据回来,这可能需要时间。 就像我做一个 cat file.tar.gz | ssh root@server "tar -zvt".

谢谢大家

最佳答案

我假设您提供的代码不是您正在使用的实际代码。 正如 wreckgar23 提到的,如果你想等待线程完成,你应该在 main 函数的末尾使用 pthread_join 。您可以删除 while(1){ sleep(1);}/pthread_exit(0),pthread_join 将使主线程等待线程完成。

同时使用 while(1)/for(;;) 也不是一个好主意。您至少可以使用一个 int 值将其设置为 0 并进行所有数据处理,直到它将其值更改为 1。您可以检查通过套接字接收的数据中的某个“消息”以获取终止命令,并将 int 的值设置为 1。(因此您可以通过(客户端)输入控制服务器的生命周期,整个服务器应用程序可以在您完成数据处理后停止。)如果您这样做,您还应该考虑安全隐患。

您还应该明确指定您使用的套接字类型。 例如,如果你使用 udp 套接字并且你有一个小缓冲区,你可能会丢失数据.. 此外,您不能同时打印缓冲区中的数据并写入其中。 (将缓冲区写入屏幕需要时间。在将数据写入屏幕时,可能会有新数据到达缓冲区并在它有机会打印之前覆盖旧数据)

关于c++ - 线程不刷新数据,在屏幕上显示数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10352030/

相关文章:

java - 为什么 SwingUtilities.invokeLater() 会导致 JButton 卡住?

ios - swift 3 : List of files Optional()

c++ - Do - Try/Catch - While block 内部有 2 个函数

c++ - 错误 C2760 : syntax error: unexpected token '<' , 预期 ';'

c - 多线程与 Matlab

c# - 对于 WinRT Metro 应用程序,相当于 Parallel.ForEach

C编程: How to create a parent directory and insert files manually?

java - 使用 DocumentBuilder 解析 InputStreamReader

c++ - C++中的PLC功能 block 库

c++ - 这个c++宏在做什么?