开发者

killing a separate thread having a socket

开发者 https://www.devze.com 2022-12-26 11:46 出处:网络
I have a separate thread ListenerThread having a socket listening to info broadcasted by some remote server. This is created at the constructor of one class I need to develop.

I have a separate thread ListenerThread having a socket listening to info broadcasted by some remote server. This is created at the constructor of one class I need to develop.

Because of requirements, once the separate thread is started I need to avoid any blocking function on the main thread. Once it comes to the point of calling the destructor of my class I cannot perform a join on the listener thread so the only thing I can do is to KILL it.

My questions are:

  1. what happens to the network resoruces allocated by the function passed to the thead? Is the socket closed properly or there might be something pending? ( most worried about this )

  2. is this procedure fast enough i.e. is the thread killed so that interrupt immediately ?

  3. I am working with Linux ...what command or what ca开发者_开发问答n I check to ensure that there is no networking resource left pending or that something went wrong for the Operating system

I thank you very much for your help

Regards MNSTN

NOTE: I am using boost::thread in C++


  1. Network resources belong to the process, not the thread, so the socket is still open.

  2. boost::thread does not have a kill method. You can only interrupt it. The effect is not immediate and depends on OS scheduler.

  3. For looking at what network resources a process holds check out lsof and netstat(8) with -p option.

The stop-signaling issue with blocking sockets as you describe is usually solved with the self-pipe trick.


When you are killing a thread, you can't be sure what resources it holds. For example, it might be holding the heap mutex; if you kill the thread, the mutex will stay locked and nobody (in your process) will be able to allocate dynamic memory, ever.

It's much better to do these things by peaceful consensus than by force. Just add a way to signal to your thread that it's not needed anymore. It can be a boost::condition. The thread would check this condition and stop when it's signalled.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号