我之前发过一个问题“在嵌入式 Linux 平台上使用 std::string 时出现段错误” https://stackoverflow.com/questions/2412667/seg-fault-when-using-stdstring-on-an-embedded-linux-platform在那里我得到了一些非常有用的建议。从那时起我就离开了其他项目,最近又开始关注这个问题。
重申一下,我只能使用 arm-linux 交叉编译器(版本 2.95.2),因为这是嵌入式平台供应商提供和支持的。我知道这个问题可能是因为 stdlib 非常旧,并且线程不是特别安全。
问题是,每当我在多个线程中使用 STL 容器时,我都会遇到分段错误。下面的代码将始终出现 seg 错误,除非我在容器声明周围使用 pthread_mutex_lock 和作用域运算符(如其他帖子中所示)。
在我的应用程序中使用这种方法是不可行的,因为我将容器传递给不同的方法和类。我理想地想解决这个问题,或者找到合适的替代方案。我尝试过STLPort和SGI的标准模板库,结果相同。我只能假设,因为它们是由非常旧的 gcc 链接的,所以它们无法解决问题。
有人有任何可能的建议或解决方案吗?或者也许您可以建议我可以将矢量(和字符串)的实现放入我的代码中?
预先感谢您的任何指导。
#include <stdio.h>
#include <vector>
#include <list>
#include <string>
using namespace std;
/////////////////////////////////////////////////////////////////////////////
class TestSeg
{
static pthread_mutex_t _logLock;
public:
TestSeg()
{
}
~TestSeg()
{
}
static void* TestThread( void *arg )
{
int i = 0;
while ( i++ < 10000 )
{
printf( "%d\n", i );
WriteBad( "Function" );
}
pthread_exit( NULL );
}
static void WriteBad( const char* sFunction )
{
//pthread_mutex_lock( &_logLock );
//{
printf( "%s\n", sFunction );
string sKiller; // <----------------------------------Bad
//list<char> killer; // <----------------------------------Bad
//vector<char> killer; // <----------------------------------Bad
//}
//pthread_mutex_unlock( &_logLock );
return;
}
void RunTest()
{
int threads = 100;
pthread_t _rx_thread[threads];
for ( int i = 0 ; i < threads ; i++ )
{
pthread_create( &_rx_thread[i], NULL, TestThread, NULL );
}
for ( int i = 0 ; i < threads ; i++ )
{
pthread_join( _rx_thread[i], NULL );
}
}
};
pthread_mutex_t TestSeg::_logLock = PTHREAD_MUTEX_INITIALIZER;
int main( int argc, char *argv[] )
{
TestSeg seg;
seg.RunTest();
pthread_exit( NULL );
}