pthreads with objects method

pthreads with objects method

本文关键字:method objects with pthreads      更新时间:2023-10-16

我有一个小问题,在我目前的项目,因为我想使用一个对象方法时创建我的线程。我认为不将此方法声明为静态方法是不可能的。你知道吗?

  public:
        CModelisation (int argc, char **argv, char[]);
    ~CModelisation ();
    void Init ();
    void *RunMainLoop (void* args);
};

CModelisation.cpp

void *CModelisation::RunMainLoop (void* args)
{
    glutDisplayFunc(Display);
    glutIdleFunc(Display);
    glutReshapeFunc(Redisplay);
    glutMotionFunc(Mouse);
    glutKeyboardFunc(Keyboard);
    glutMainLoop();
    return args;
}
主要

    threads[1] = new CThread();
    threads[1]->exec(Model->RunMainLoop,(void*)1);

谢谢!

我认为为任何线程方法创建包装器函数是一种常见的做法:

struct Foo {
    void someMethod() {
        // ... the actual method ...
    }
    static void* someMethodWrap(void* arg) {
        ((Foo*) arg)->someMethod();
        return 0;
    }
    void callSomeMethodInOtherThread() {
        pthread_create(thread, attr, someMethodWrap, this);
    }
};

传递额外的参数需要更多的努力,但这是一般的想法。

幸运的是,下一个标准的std::thread使我们的生活更容易…但这仍是未来的事