user3626411
user3626411

Reputation: 198

Create boost::thread without callable object

I would like to create boost::thread without passing callable object to constructor ( not-any-thread state ).

boost::shared_ptr<boost::thread> ThreadHandle_.reset( new boost::thread() );

but how can i later pass callable object ?

Upvotes: 0

Views: 102

Answers (2)

sehe
sehe

Reputation: 392979

void foo() { }

boost::thread th; // not-any-thread

th = boost::thread(foo); // bound

You can do exactly the same with the shared ptr complication

Upvotes: 1

alexbuisson
alexbuisson

Reputation: 8469

You can create your own wrapper on top of boost::thread, something similar to:

class QThread
{
public:
    QThread();
    virtual ~QThread();
    void operator()(const boost::function0<void>& action);

  void Join();

private:
    void Process();

    std::list<boost::function0<void> > m_Queue;
    bool m_Destroy;
    boost::condition_variable_any m_Available;
    boost::mutex     m_QueueLock;
    boost::barrier   m_Barrier;
    boost::thread    m_Thread;
};

and implement Process in a way it wait until you put something to do ( a task, as a callable function in the queue)

void QThread::Process()
{
    m_Barrier.wait();
    boost::mutex::scoped_lock lock(m_QueueLock);
    while(!m_Destroy)
    {
        while(!m_Destroy && !m_Queue.empty())
        {
            boost::function0<void> action = m_Queue.front();
            m_Queue.pop_front();
            lock.unlock();
            action();
            lock.lock();
        }

    if (!m_Destroy)
    {
        m_Available.wait(lock);
    }
    }
}

Upvotes: 1

Related Questions