我有下面的代碼來獲取核心轉儲錯誤。每個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;
}
mascoj你是對的,那個參數是指向一個類實例的指針,我當時馬虎不在。 。 – eral