gpt4 book ai didi

c++ - 带有 posix 线程的嵌入式 ARM 上的奇怪段错误需要智能答案

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:40:54 26 4
gpt4 key购买 nike

最近几天我一直在研究一个奇怪的段错误。以下代码在我运行 Linux 的 PC 上运行良好。但是使用我们的嵌入式设备制造商提供的 ARM 交叉编译器,它在例程 s() 中给出了段错误。 SIGSEGV 发生在 std::string 的销毁处。如果将它作为变量传递,也会发生这种情况。然而,对于非 STL 类(例如 int),一切正常。

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


arm-linux-g++ -Wall -otest -lpthread
arm-linux-strip test

欢迎所有建议!


using namespace std;

void *ExecuteThreadMethod(void *AThread);

class Thread
{
private:
pthread_t internalThread;
sem_t finishedSemaphore;
public:
bool Terminated;
Thread()
{
Terminated = false;
sem_init (&finishedSemaphore, 0, 0);
}
~Thread()
{
sem_destroy (&finishedSemaphore);
}

void RunSigSegv() // <----- with the try...catch it causes a SIGSEGV in routine s() below
{
try
{
while (!Terminated)
{
cout << "ExecuteLooped" << endl;
}
sem_post(&finishedSemaphore);
}
catch(...)
{
}
}

void RunOk() // <----- without the try...catch, it runs fine
{
while (!Terminated)
{
cout << "ExecuteLooped" << endl;
}
sem_post(&finishedSemaphore);
}

void Start()
{
pthread_attr_t _attr;

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

void Terminate()
{
Terminated = true;
sem_wait(&finishedSemaphore);
}
};

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

Thread _thread;

void s()
{
string Test;
_thread.Start();
} // <----- destruction of std::string Test causes a SIGSEGV, without try...catch in the thread this doesn't happen

void t()
{
_thread.Terminate();
}

int main(void)
{
s();
t();
}

最佳答案

不要使用-lpthread。这仅与提供线程处理函数的库链接。全线程支持可能需要更多,例如与 libstdc++ 的特殊线程安全版本链接,或为线程局部变量访问保留特定寄存器。

对于 gcc 或 g++,使用 -pthread 命令行标志,用于编译和链接。这将指示 gcc 执行任何必要的操作以启用可靠的线程,包括但不限于在需要时添加 -lpthread 标志。

关于c++ - 带有 posix 线程的嵌入式 ARM 上的奇怪段错误需要智能答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3958196/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com