在 C++ 中的特定线程上执行函数
Executing a function on a specific thread in C++
我有一个 class,它有一些线程安全的功能。
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;
}
classA可以在不同的线程上设置。由于 class C 是线程特定的,我想从线程 m_id
.
运行 somefun
所以我想通过将 somefun 提交给 m_id 标识的线程来执行 somefun。
主要问题是,如果我知道线程的线程 ID ,我可以 运行 实时线程上的特定函数吗?
您可以使用 boost::asio::io_service.
发布在一个线程上的函数(或工作)将在另一个线程上执行(在该线程上调用 io_service 的 run()
成员函数)。
一个粗略的例子:
#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;
});
I was thinking of executing somefun by submitting somefun to the thread identified by m_id
.
线程通常不是这样工作的。你不能只要求任何线程停止它正在做的事情并调用某个函数。向线程提交任何内容的唯一方法是线程已经是 运行 旨在接受提交的代码,并且知道如何处理它。
您可以编写一个永远循环的线程,在每次迭代中它等待从阻塞队列中消耗一个 std::function<...>
对象,然后调用该对象。然后,一些其他线程可以通过将对象放入队列来“提交”std::function<...>
对象给线程。
我有一个 class,它有一些线程安全的功能。
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;
}
classA可以在不同的线程上设置。由于 class C 是线程特定的,我想从线程 m_id
.
somefun
所以我想通过将 somefun 提交给 m_id 标识的线程来执行 somefun。
主要问题是,如果我知道线程的线程 ID ,我可以 运行 实时线程上的特定函数吗?
您可以使用 boost::asio::io_service.
发布在一个线程上的函数(或工作)将在另一个线程上执行(在该线程上调用 io_service 的 run()
成员函数)。
一个粗略的例子:
#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;
});
I was thinking of executing somefun by submitting somefun to the thread identified by
m_id
.
线程通常不是这样工作的。你不能只要求任何线程停止它正在做的事情并调用某个函数。向线程提交任何内容的唯一方法是线程已经是 运行 旨在接受提交的代码,并且知道如何处理它。
您可以编写一个永远循环的线程,在每次迭代中它等待从阻塞队列中消耗一个 std::function<...>
对象,然后调用该对象。然后,一些其他线程可以通过将对象放入队列来“提交”std::function<...>
对象给线程。