使用 Boost 库的 C++ 线程

标签 c++ multithreading boost

我希望我的函数在单独的线程中运行。我使用 Boost 库并在我的 main.cpp 中包含这样的内容:

#include <boost/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

我希望线程像这样开始:

boost::thread ethread(Engine::function,info);
// info is an object from the class Engine and i need this in the
// function

我的 Engine 类在 func.h 中,函数如下所示:

void Engine::function(Engine info)
{
    //STUFF
    boost::this_thread::sleep(boost::posix_time::milliseconds(1));
}

顺便说一句:线程的 sleep 函数是否正确?

每次我想编译它都会给我这个错误:

error C3867: "Engine::function": function call missing argument list; use '&Engine::function' to create a pointer to member

我试图在线程中使用&Engine::function 出现这个错误:

error C2064: term does not evaluate to a function taking 2 arguments

我也试过:

boost::thread ethread(Engine::function,info, _1);

然后出现这个错误:

error C2784: "result_traits<R,F>::type boost::_bi::list0::operator [](const boost::_bi::bind_t<R,F,L> &) const"

有人可以帮我解决这个问题吗?我只想在主线程旁边运行该函数。

最佳答案

您应该使用绑定(bind)函数来创建带有指向类成员函数的指针的功能对象,或者使您的函数静态化。

http://ru.cppreference.com/w/cpp/utility/functional/bind

更详细的解释: boost::thread 构造函数需要指向函数的指针。如果是普通函数,语法很简单:&hello

#include <boost/thread/thread.hpp>
#include <iostream>
void hello()
{
    std::cout << "Hello world, I'm a thread!" << std::endl;
}

int main(int argc, char* argv[])
{
    boost::thread thrd(&hello);
    thrd.join();
    return 0;
}

但是如果您需要指向类函数的指针,您必须记住此类函数具有隐式参数 - this 指针,因此您也必须传递它。您可以通过使用 std::bind 或 boost bind 创建可调用对象来做到这一点。

#include <iostream>
#include <boost/thread.hpp>

class Foo{
public:
    void print( int a )
    {
        std::cout << a << std::endl;
    }
};

int main(int argc, char *argv[])
{
    Foo foo;
    boost::thread t( std::bind( &Foo::print, &foo, 5 ) );
    t.join();


    return 0;
}

关于使用 Boost 库的 C++ 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763372/

相关文章:

c++ - 使用BOOST::serialization将二进制存档写入共享内存

c++ - 为什么 C++11/Boost `unordered_map` 在删除时不重新散列?

c++ - 基本 boost 正则表达式问题

c++ - 在 C++ 中使用 map() 时出错

c++ - 图实现 C++

java - 多个线程可以同时将数据写入文件吗?

java - 从使用线程的另一个类检索 String 时出现问题

c++ - 多次使用 header 不好吗?

c++ - 如何有选择地从缓冲区中读取数据

c++ - C++中的单例多线程代码