I have a UDP multicast receiver that will start an std::thread
then detach()
it to handle the receiving of messages, and it should be able to interrupt the blocking call when called upon.
void startThread()
{
if(flagIsNotset)
{
//set flag
std::thread t(&receiveData, this, socketDetails);
t.detach();
}
}
void receiveData(socketDetails)
{
//initilaise socket
//bind socket to interface
//binds multicast address & port to interface
while(true)
{
//recvfrom(...)
//handle received data
}
//prints a message to know that the thread has exited the while loop
//unset flag
}
void interrupt()
{
//unset flag is shifted here after realizing it did not reach the end of receiveData() when closesocket was called for the first time.
closesocket(s);
}
everything was fine, I can receive UDP messages etc. but when interrupt is first called: it does not reach the message printing part & setting flag portion. when I shift the //set flag codes to interrupt()
, I can confirm that for the first time (of calling interrupt()
then startThread()
), the message is not printed but on subsequent calls, it reached the end of the receiveData function as intended.
My question are as follows :
1) What happened to the first thread that was detached? is it stuck in recvfrom
forever and was not interrupted by closesocket()
?
2) Will this cause memory leaking ? that is my primary concern...as I am unable to figure out the state of the first thread that was detached, will setting the thread t as a private member and calling the t::~thread()
in interrupt()
helps to ensure that the thread is terminated when interrupt is called?
3) Repeating startThread()
and interrupt()
does not seems to create a duplicate thread that is listening from the same socket. (i.e always receive one copy of the multicast message)
4) If there is any suggestions to improve this code, please feel free to comment.