下面的代码编译和运行在标准Linux:机器人+并行线程+ C++ = SIGSEGV
#include <iostream>
#include <pthread.h>
using namespace std;
class Foo
{
public:
Foo();
void go_thread();
void stop_thread();
private:
static void* worker(void* param);
pthread_t m_pt;
};
Foo::Foo()
{
m_pt = 0;
}
void Foo::go_thread()
{
int success = pthread_create(&m_pt, NULL, worker, static_cast<void*>(this));
if(success == 0)
{
cout << "thread started" << endl;
}
}
void Foo::stop_thread()
{
int success = pthread_join(m_pt, NULL);
if(success == 0)
{
cout << "thread stopped" << endl;
}
}
void* Foo::worker(void* p)
{
cout << "thread running" << endl;
return 0;
}
int main()
{
Foo f;
f.go_thread();
f.stop_thread();
return 0;
}
和产生以下输出:
$ ./a.out
thread started
thread running
thread stopped
$
此代码还构建了Android NDK(R5B )。但是,当adb将生成的可执行文件推送到设备并运行它时,我在main()运行之前就会获得一个SIGSEGV。我已经将问题隔离到了pthread_create()
看来,在我的代码中只是存在这个调用,而不介意执行,导致我的编程陷入错误。有任何想法吗?
你的错误检查是错误的。 pthread_create&join将在成功时返回0,否则为表示错误的整数。你可能因为某个原因失败,不知道它。 – Duck 2011-04-05 03:48:51
是的,好眼睛。我纠正了这个帖子,但核心问题仍然存在。谢谢! – awm129 2011-04-05 04:00:53