类中的 pthread 函数

新手上路,请多包涵

假设我有一个课程,例如

class c {
    // ...
    void *print(void *){ cout << "Hello"; }
}

然后我有一个 c 向量

vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());

现在,我想在 c.print();

以下是给我以下问题:

pthread_create(&t1, NULL, &c[0].print, NULL);

错误输出:无法将参数 ‘3’ 的 ‘void* (tree_item::*)(void*)’ 转换为 ‘void* (*)(void*)’ 到 ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(无效*), 无效*)’

原文由 Angel.King.47 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 694
2 个回答

您不能按照您编写的方式进行操作,因为 C++ 类成员函数有一个隐藏的 this 传入的参数 pthread_create() 不知道 this 的值 --- 使用,所以如果你试图通过将方法转换为适当类型的函数指针来绕过编译器,你会得到一个分段错误。您必须使用静态类方法(没有 this 参数)或普通函数来引导类:

 class C
{
public:
    void *hello(void)
    {
        std::cout << "Hello, world!" << std::endl;
        return 0;
    }

    static void *hello_helper(void *context)
    {
        return ((C *)context)->hello();
    }
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);

原文由 Adam Rosenfield 发布,翻译遵循 CC BY-SA 2.5 许可协议

这是一个有点老的问题,但却是许多人面临的一个非常普遍的问题。以下是使用 std::thread 处理此问题的简单而优雅的方法

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

class foo
{
    public:
        void bar(int j)
        {
            n = j;
            for (int i = 0; i < 5; ++i) {
                std::cout << "Child thread executing\n";
                ++n;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
        int n = 0;
};

int main()
{
    int n = 5;
    foo f;
    std::thread class_thread(&foo::bar, &f, n); // t5 runs foo::bar() on object f
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    std::cout << "Main Thread running as usual";
    class_thread.join();
    std::cout << "Final value of foo::n is " << f.n << '\n';
}

上面的代码还负责将参数传递给线程函数。

有关更多详细信息,请参阅 std::thread 文档。

原文由 pankaj 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题