2016-12-01 44 views
0

我有下面的代码来获取核心转储错误。每个C实例创建自己的线程然后运行。我猜静态函数和类参数“count”有问题。当我注释掉打印它的代码时,没有发生故障。在类中使用pthreads时出现分段错误

#include <iostream> 
    #include <pthread.h> 
    using namespace std; 

    class C { 
     public: 
     int count; 
     C(int c_): count(c_){} 
    public: 
     void *hello(void) 
     { 
      std::cout << "Hello, world!" <<std::endl; 
      std::cout<<count; // bug here!!! 
      return 0; 
     } 

     static void *hello_helper(void *context) 
     { 
      return ((C *)context)->hello(); 
     } 

     void run() { 

      pthread_t t; 
      pthread_create(&t, NULL, &C::hello_helper, NULL); 
     } 

    }; 

    int main() { 

    C c(2); 
    c.run(); 

    C c2(4); 
    c2.run(); 

    while(true); 

    return 0; 
    } 

回答

1

决定写一个答案。你打电话hello_helpercontextNULL根据你如何创建你的线程。 C++完全允许您在空指针上调用成员函数,除非访问成员元素,否则不会发生错误。

在你的情况下,通过添加行打印count。你现在正在访问一个空指针的成员变量,这是一个很大的禁忌。

这里是你就要用什么样的例子:

#include <iostream> 
class Rebel 
{ 
    public: 
    void speak() 
    { 
     std::cout << "I DO WHAT I WANT!" << std::endl;   
    }  
}; 
int main() 
{ 
    void * bad_bad_ptr = NULL; 
    ((Rebel*)bad_bad_ptr)->speak(); 
} 

输出:

I DO WHAT I WANT!

通过修改您的pthread_create调用以传递this指针(即pthread_create(&t, NULL, &C::hello_helper, this);,你现在有一个有效的实例来访问成员变量。

+0

mascoj你是对的,那个参数是指向一个类实例的指针,我当时马虎不在。 。 – eral

-1

我通过在创建线程时将此指针传递给NULL来解决此问题。我猜os在前一种情况下创建了两次相同的线程?

+1

不,你正在调用''''hello_he ''''''''''NULL''''的背景..... – mascoj

+0

为什么这么重要?当我不打印计数变量时,这是可以的。 – eral

+0

为了使这个答案更有用(并且减少了诱饵诱饵),我建议添加你改变的代码,改变它的代码,并解释如何解决你的问题。 – user4581301