So I am learning std::thread in C++ 11 and I want to use it with std::vector on my socket programming.
I've search for std::thread tutorial and it seems to me that many people are using std::thread with containers, such as std::vector.
My problem is:
-
What is benefit of using std::thread with std::vector?
-
I am implementing my C++ socket server with std::thread and std::vector (code below), and I found out a problem:
If a client connect to my server, my server will create a thread and store it in std::vector, which will increase size of std::vector. If that client disconnected and reconnect to my server again, it will create a thread again for that connection and increase std::vector size. However, elements remain even if thread is done. So, if a client repeatedly connect/disconnect to my server, the size of std::vector will increase until the machine runs out of memory. Is there a way to detect a thread is complete(or client disconnected) and delete the element of std::vector?
Below is my implementation: assume all TCP set up are done and the socket listening part looks like this:
// things to do after connection established
void do_something(int sockfd)
{
// do something
}
int main()
{
/* ------------
TCP socket setup here ...
------------*/
std::vector <std::thread> MyThreads;
// server waiting for connections
while(1)
{
std::cout << "Listening..." << std::endl;
new_sockfd = accept(socked, (struct sockaddr *)&ClientAddress, &len);
MyThreads.push_back(std::move(std::thread(do_something, new_sockfd)));
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire