Boost logo

Boost Users :

Subject: [Boost-users] Is the following use of boost::function<> safe?
From: David Goodenough (dgnuff_at_[hidden])
Date: 2013-12-09 03:09:02


Let me preface this with the note that the whole idea behind what I'm
trying to do is invoke an arbitrary function in a new thread, optionally
delaying the invocation by some number of milliseconds

That said,

----- threadrun.h -----
#ifndef _THREADRUN_H_
#define _THREADRUN_H_

#include <boost/function.hpp>

namespace Thread
{
void ThreadRun(boost::function<void()> const &job);
void ThreadDelayedRun(boost::function<void()> const &job, unsigned int
delay);
};

#endif
----- threadrun.h -----

----- threadrun.cpp -----
#include "threadrun.h"

static void DelayedRun(boost::function<void()> job, unsigned int delay)
{
    Sleepms(delay); // Routine available elsewhere that simply sleeps for
delay ms
    job();
}

namespace Thread
{
void ThreadRun(boost::function<void()> const &job)
{
    boost::thread thr = boost::thread(job);
    thr.detach(); // Not really necessary, but it does make it
explicit that we'll never wait for the thread to finish
}

void ThreadDelayedRun(boost::function<void()> const &job, unsigned int
delay)
{
    boost::thread thr = boost::thread(boost::bind(DelayedRun, job, delay));
    thr.detach(); // Not really necessary, but it does make it
explicit that we'll never wait for the thread to finish
}

};
----- threadrun.cpp -----

Use cases would be:

void myFunc(int a, int b)
{
    ...
}

int myFunc1(int a, int b)
{
    ...
    return x
}

    Thread::ThreadRun(boost::bind(myFunc, 1000, 17));
    Thread::ThreadDelayedRun(boost::bind(myFunc1, 2000, 42), 5000);

This appears to work correctly, I'm currently using boost 1.54 - haven't
build 1.55 yet, but will do so in the near future. My only concern is the
second case where I have myFunc1() whose return type is int, yet in the
prototype for ThreadDelayedRun() I'm making it look a whole lot like it's
void.

The return type ultimately doesn't matter since this is specifically
designed to be a "fire and forget" system, which means that any return
value will be lost, there's no way for the invoking thread to recover it.

So, is there anything dangerous about what I'm doing?



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net