pr0py_s
pr0py_s

Reputation: 171

Executing a function on a specific thread in C++

I have a class which has some of its functions thread-safe.

class A 
{
    public:
    // Thread Safe class B
    B foo;
    // Thread specific class C
    C bar;

    void somefunc()
    {
        // uses foo and bar
    }
}

class C
{
    public:
    C()
    {
        m_id = std::this_thread::get_id();
    }

    // id of the thread which created the class
    std::thread::id m_id;
}

class A can be set on different threads. As class C is thread-specific I want to run somefun from the thread m_id.

So I was thinking of executing somefun by submitting somefun to the thread identified by m_id.

The main question is can I run a particular function on a live thread given that I know the thread id of the thread?

Upvotes: 1

Views: 1609

Answers (2)

Solomon Slow
Solomon Slow

Reputation: 27115

I was thinking of executing somefun by submitting somefun to the thread identified by m_id.

That is not how threads work in general. You can't ask just any thread to stop what it is doing and call a certain function. The only way that it makes sense to submit anything to a thread is if the thread is already running code that is designed to accept the submission and, that knows what to do with it.

You could write a thread that loops forever, and on each iteration it waits to consume a std::function<...> object from a blocking queue, and then it calls the object. Then, some other thread could "submit" std::function<...> objects to the thread by putting them in the queue.

Upvotes: 2

abhiarora
abhiarora

Reputation: 10430

You can use boost::asio::io_service.

A function (or work) posted on a thread will be executed on a different thread (on which run() member function of io_service is called).

A Rough Example:

#include <boost/asio/io_service.hpp>

boost::asio::io_service ios_;

void func(void)
{
    std::cout << "Executing work: " << std::this_thread::get_id() << std::endl;
}

// Thread 1
ios_.run();

// Thread 2
std::cout << "Posting work: " << std::this_thread::get_id() << std::endl;
ios_.post(func);

ios_.port([] () {
    std::cout << "Lambda" << std::endl;
});

Upvotes: 1

Related Questions