下面的代碼編譯和運行在標準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