Difference between revisions of "Short Notes on C/C++"

From PaskvilWiki
Jump to: navigation, search
(Created page with "== How to clean up after child thread == Even when the child thread shuts down gracefully - i.e. the thread's function returns, or the thread calls <tt>pthread_exit()</tt> - the...")
(No difference)

Revision as of 21:09, 1 June 2012

How to clean up after child thread

Even when the child thread shuts down gracefully - i.e. the thread's function returns, or the thread calls pthread_exit() - there might still be a memory leak due to the thread data allocated during the call to pthread_create().

There are 3 options to handle this:

  • stop the thread from the creator thread using pthread_cancel(),
  • wait for the thread to shut down gracefully, and then pthread_join() with the thread (yes, "join with the stopped thread"); this call returns immediately, and frees up thread's resources,
  • have the thread clean up on its own, by pthread_detach()-ing the thread.

Non-blocking IO using sockets

To get a non-blocking IO, you can

  • set the socket to non-blocking:
// for fcntl()
#include <unistd.h>
#include <fcntl.h>
// for ioctl()
#include <sys/ioctl.h>

int set_nonblocking(int fd)
{
    int flags;
#if defined(O_NONBLOCK)
    if (-1 == (flags = fcntl(fd, F_GETFL, 0)))
        flags = 0;
    return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
#else
    flags = 1;
    return ioctl(fd, FIOBIO, &flags);
#endif
}
  • or, you can use MSG_DONTWAIT as flags in the calls to recv(), recvfrom(), send(), and sendto().

Or both... can't hurt. ;-)