【问题标题】:C++ with pthread executing a member function使用 pthread 执行成员函数的 C++
【发布时间】:2013-02-22 12:40:00
【问题描述】:

我想用 c++ 编写一个带有 pthreads 的小测试程序,我没有 pthreads 的经验,但到目前为止我读到的是存在问题,因为 pthreads 是 C 构造。

我的代码如下:

class A{
       public:
            int main();
            void* do_work();
            static void* helper_do_work(void*);
};

void * IMagFieldSvc::do_work(){
}

void* IMagFieldSvc::helper_do_work(void* context)
{
          return ((IMagFieldSvc*)context)->do_work();
}
int A::main(){
…
          pthread_create(&thread, &attr, &helper_do_work, &svc);
          pthread_join(thread, NULL);
}

但编译时使用:

g++ -pthread test.cxx

返回

/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../lib64/crt1.o:在函数_start': (.text+0x20): undefined reference tomain' collect2: ld 返回 1 个退出状态

我尝试添加

extern "C" void* helper_do_work(void*);

不管这个做什么,但错误是一样的

打嗝?

不知道我是否应该为此打开一个单独的问题: 另外,在 do_work 中我想访问和更改成员变量,练习的全部目的是找出我如何访问和更改成员变量,使它们使用 __thread 成为线程局部变量。这些成员变量是具有自己的构造函数和析构函数的自定义类型,我不知道为什么会有所不同,但显然它确实......

【问题讨论】:

  • 好吧,对于初学者来说,错误是说你没有main() 函数。你似乎有一个A::main(),但没有一个全局的main()...
  • 请注意,这与线程完全无关!
  • 不需要extern "C"。像您在初始代码中的普通静态成员就可以了。但是,main 不是。

标签: c++ pthreads


【解决方案1】:

main 不能是成员函数,它必须定义在全局命名空间中。

这样定义:

int main()
{
// ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多