在 class 中使用 pthread 时出现分段错误
segmentation fault while using pthreads in class
我有以下代码导致核心转储错误。每个 C 实例创建自己的线程然后运行。我想静态函数和 class 参数 "count" 有问题。当我注释掉打印它的代码时,没有发生错误..
#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;
}
我通过在创建线程时传递此指针而不是 NULL 来解决问题。我想 os 在前一种情况下创建了两次相同的线程?
决定写一个答案。根据您创建线程的方式,您调用 hello_helper
的 context
为 NULL
。 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);
,您现在有一个有效的实例来访问成员变量。
我有以下代码导致核心转储错误。每个 C 实例创建自己的线程然后运行。我想静态函数和 class 参数 "count" 有问题。当我注释掉打印它的代码时,没有发生错误..
#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;
}
我通过在创建线程时传递此指针而不是 NULL 来解决问题。我想 os 在前一种情况下创建了两次相同的线程?
决定写一个答案。根据您创建线程的方式,您调用 hello_helper
的 context
为 NULL
。 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);
,您现在有一个有效的实例来访问成员变量。