首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pthreads和C++

pthreads和C++
EN

Stack Overflow用户
提问于 2010-03-18 15:23:26
回答 2查看 445关注 0票数 1

我正在使用C++和pthread,到目前为止一切都很好。如果类成员函数是静态的,我可以访问它,并且我已经读到,如果我将" this“作为参数传递给pthread_create,就可以访问普通的类成员函数,因为c++在幕后这样做。但我的问题是,我想给这个函数一个整数,而我不知道如何用pthread_create做多个参数。

EN

回答 2

Stack Overflow用户

发布于 2010-03-18 15:41:37

传递一个struct指针。

代码语言:javascript
复制
struct Arg {
  MyClass* _this;
  int      another_arg;
};

...

Arg* arg = new Arg;
arg->_this = this;
arg->another_arg = 12;
pthread_create(..., arg);
...
delete arg;
票数 6
EN

Stack Overflow用户

发布于 2013-05-09 00:58:18

您可以尝试使用boost线程库并使用boost::bind()这里有一个示例,

代码语言:javascript
复制
class MyThread
{
public:
    MyThread( /* Your arguments here */) : m_thread(NULL)
    {
        m_thread = new boost::thread(boost::bind(&MyThread::thread_routine, this));
    }

    ~MyThread()
    {
        stop();
    }

    void stop()
    {
        if (m_thread)
        {
            m_thread->interrupt(); 
            m_thread->join();
        }
    }

private:
    void thread_routine() {... /* you can access a/b here */}


private:
    int a;
    int b;
    boost::thread *m_thread;
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2468113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档