当前位置: 动力学知识库 > 问答 > 编程问答 >

multithreading - Thread does not work correctly in chat application using c++

问题描述:

I'm making a chat application client part using boost library and fltk for GUI. I make class for the client part and using thread to handle GUI from freezing

the thread for the read part contain an infinite loop that waits to read from the server so i used the thread for this function in the client class

the code i use

this is the thread in the constructor of client.cpp

#include "Client.h"

Client::Client(string ip, int port) :

socket(ios),

ep(asio::ip::address::from_string("127.0.0.1"),5002)

{

this->ip = "127.0.0.1";

this->port = 5002;

socket.connect(ep);

thread t(&Client::run,this); // here the thread

t.detach(); // i use detach to make it run alone so my app not wait it

}

and this the run function which have the infinite loop waiting for to read from the server and added to the thread to not freez the GUI

void Client::run()

{

while (true) {

asio::streambuf buf;

int read = asio::read_until(socket, buf, '\n');

string message;

istream in(&buf);

getline(in, message);

message.append("\n");

buffer->append(message.c_str());

}

}

the problem is that when I send a message it didn't come at the same time. it comes after some seconds may I sent 4 or 5 message they received together not as java when I make run function and the class extends thread I use an infinite loop in it the message comes at the same time and fast so what should I do to solve this problem, please I need help because I'm beginners in threads

Thanks in advance

分享给朋友:
您可能感兴趣的文章:
随机阅读: