1

可能重复:
类中的 pthread 函数

由于以下行,我有无法编译的代码pthread_create

void* gtk_functor::_threaded_run(void* win)
{
    Gtk::Window* w = static_cast<Gtk::Window*>(win);
    Gtk::Main::run(*w);
    delete w;
}

void gtk_functor::operator ()(Gtk::Window& win, bool threaded)
{
    if (threaded)
    {
        pthread_t t_num;
        pthread_create(&t_num, NULL, (void* (*)(void*))&gtk_functor::_threaded_run, static_cast<void*>(&win));
    }
    else
    {
        Gtk::Main::run(win);
    }
}

这个 gcc 行:

g++ -o main 'pkg-config --cflags --libs sqlite3 gtkmm-3.0' -lpthread main.cpp

最后用这个输出编译:

code/ui.cpp: In member function 'void ui::gtk_functor::operator()(Gtk::Window&, bool)':
code/ui.cpp:45:65: warning: converting from 'void* (ui::gtk_functor::*)(void*)' to 'void* (*)(void*)' [-Wpmf-conversions]

显然代码无法正常工作,我在引发sementation fault时得到。if (threaded)

我知道它的演员阵容,但我不知道将成员函数传递给 pthread_create 的正确形式。有什么建议么?

4

2 回答 2

5

尝试制作_threaded_run静态。在标题中:

private:
  static void* _threaded_run(void*);

在实施中:

void* gtk_functor::_threaded_run(void* win) {
  Gtk::Window* w = static_cast<Gtk::Window*>(win);
  Gtk::Main::run(*w);
  delete w;
}

然后在创建线程时:

pthread_create(&t_num, NULL, &gtk_functor::_threaded_run, static_cast<void*>(&win));
于 2012-07-17T18:42:50.450 回答
5

正如@ildjarn 建议的那样,只需创建一个免费功能:

void * threaded_run(void * win)
{
    Gtk::Window * const w = static_cast<Gtk::Window*>(win);
    Gtk::Main::run(*w);
    delete w;
}

// ...

pthread_create(&t_num, NULL, threaded_run, &win);

由于该函数不依赖于任何特定gtk_functor对象的状态,因此将其设为成员函数是没有意义的。


在一个假设的不同世界中,您确实希望在单独的线程中调用对象的成员函数,您需要以某种方式传递对象的对象引用,通常通过参数 void 指针:

struct Foo
{
    void * run() { /* ... use state ... */ }

    /* ... state ... */
};

Foo x;
pthread_t pt;

// start a new execution context with x.run():
pthread_create(&pt, NULL, FooInvoker, &x);

extern "C" void * FooInvoker(void * p)
{
    return static_cast<Foo*>(p)->run();
}

事实上,您甚至可能希望将更多上下文信息打包到某个辅助结构中,并将指向该结构的 void 指针传递线程调用函数。

于 2012-07-17T18:37:45.117 回答