尝试... catch会导致嵌入式ARM上的posix线程出现分段错误

时间:2010-10-18 14:50:39

标签: linux multithreading gcc posix arm

今天,我在销毁std :: string后发布了有关分段错误的问题(请参阅this post)。我已经删除了代码,以便我不使用STL,但有时仍会出现分段错误。

以下代码在运行Linux的PC上运行正常。但是使用嵌入式设备制造商提供的ARM交叉编译器,它会在catch (...)之前发出分段错误。

此问题似乎与Google网上论坛中的this post有关联,但我还没有找到任何解决方案。

使用ARM交叉编译器编译代码

仍然欢迎任何建议!


#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

void *ExecuteThreadMethod(void *AThread);

class Thread
{
  private:
    pthread_t internalThread;
  public:
    void RunSigSegv()
    {
      try
      {
        for (int i = 0; i < 200; i++)
        {
          usleep(10000);
        }
      } // <---- Segmentation fault occurs here
      catch(...)
      {
      }
    }

    void Start()
    {
      pthread_attr_t _attr;

      pthread_attr_init(&_attr);
      pthread_attr_setdetachstate(&_attr, PTHREAD_CREATE_DETACHED);
      pthread_create (&internalThread, &_attr, ExecuteThreadMethod, this);
    }
};

void *ExecuteThreadMethod(void *AThread)
{
  ((Thread *)AThread)->RunSigSegv();
  pthread_exit(NULL);
}

Thread _thread1;
Thread _thread2;
Thread _thread3;
Thread _thread4;

void s()
{
  _thread1.Start();
  _thread2.Start();
  _thread3.Start();
  _thread4.Start();
}

int main(void)
{
  s();
  usleep(5000000);
}

2 个答案:

答案 0 :(得分:1)

我曾经遇到过像这样的问题,这是由于libstdc++版本与没有线程支持的版本相关联,这意味着所有线程共享一个共同的异常处理堆栈,带来灾难性的后果。

确保交叉编译器及其库配置为--enable-threads=posix

答案 1 :(得分:0)

只是一个诊断问题:如果你没有在Start()中分离线程会发生什么?你必须将线程pthread_join()放回main()。

另外,您考虑过Boost's threads了吗?这可能更合适,因为你使用的是C ++而不是C。