在多线程中使用标准C++ string类型中substr时怎么总是异常?详情请进!

vc8 2004-04-30 10:31:33
线程类样内容:
void thread()
{
string str1, str2;
str1 = "349ejoasdiufo93809384oiiahejf98374aoishfd";
while(1 )
{
str2 = str1.substr( 0, 16 );
}
}
我起50个线程一会程序就会异常,最终定位到operator new 或 poerator delete
请问是new 或delete 不支持多线程吗?还是其他什么原因应如何解决?多谢
...全文
1311 11 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
wingfiring 2004-04-30
  • 打赏
  • 举报
回复
vc6中的stl不是线程安全的,换成stlport看看。
vc8 2004-04-30
  • 打赏
  • 举报
回复
to jinhao
我试了用try catch,能捕获到异常但程序还是异常
只要一个线程异常,其他线程就都异常了.
捕获到异常后,在循环回去后执行str1.substr(...)时,还是异常。
Jinhao 2004-04-30
  • 打赏
  • 举报
回复
void thread()
{
try{
string str1, str2;
str1 = "349ejoasdiufo93809384oiiahejf98374aoishfd";
while(1 )
{
str2 = str1.substr( 0, 16 );
}
}catch(std::bad_alloc){ //或catch(...)
//捕捉异常
}
}
vc8 2004-04-30
  • 打赏
  • 举报
回复
to ejiue
还是不行,还是异常
ejiue 2004-04-30
  • 打赏
  • 举报
回复
应该是执行str2 = str1.substr( 0, 16 );时,
str1.substr( 0, 16 )动态分配了一块空间来存储返回的子字符串。
而且每一次执行时都没有释放原来的空间。

你用50个线程不停的循环,可能造成堆分配的时候冲突。所以出异常。

在str2 = str1.substr( 0, 16 );语句前,加入str2.Empty();
把str2原来的空间释放掉。
这样试试看。
vc8 2004-04-30
  • 打赏
  • 举报
回复
我用的是2000
pacman2000 2004-04-30
  • 打赏
  • 举报
回复
你用的什么操作系统啊?
vc8 2004-04-30
  • 打赏
  • 举报
回复
如果想加异常处理,应如何做?
Wolf0403 2004-04-30
  • 打赏
  • 举报
回复
是异常还是访问错误?
cancer001 2004-04-30
  • 打赏
  • 举报
回复
void thread()
{
try{
string str1, str2;
str1 = "349ejoasdiufo93809384oiiahejf98374aoishfd";
while(1 )
{
str2 = str1.substr( 0, 16 );
}
}catch(std::bad_alloc){ //或catch(...)
//捕捉异常
}
}

基本的异常处理机制,引用辣子鸡丁的代码
rorot 2004-04-30
  • 打赏
  • 举报
回复 1
旧式得字符串string不是线程安全得,一个线程得执行权可能在任何时候被抢占,这包括一个string操作执行到中间得时候。由于楼主得线程函数里得字符串对象str2事先没有足够得空间容纳16个字符,导致了在执行substr()函数时对str2对象扩充空间,再加上substr()函数从而导致了动态内存分配。而线程执行权得抢占又导致了堆内存得异常

我觉得一个简单方法就是给str2预先分配足够得内存,保证他在线程函数里不动态扩充.
---------------------------
#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

// 线程函数
DWORD WINAPI Thread(void *ptr)
{
string str1, str2(17, 0);
str1 = "349ejoasdiufo93809384oiiahejf98374aoishfd";

while( 1 )
{
for (int i=0; i<16; ++i )
str2[i] = str1[i];
}
return 0;
}

int main()
// 旧式string多线程安全测试
{
// 开100个线程
const int nThread = 100;
HANDLE hThread[nThread];

for ( int i=0; i<nThread; ++i )
hThread[i] = CreateThread(
NULL,
0,
(DWORD (WINAPI *)(void*))Thread,
NULL,
0,
NULL );

// 主线程睡眠
Sleep( 1000 );
// 释放句柄
for ( i=0; i<nThread; ++i )
CloseHandle( hThread[i] );

return 0;
}

24,860

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 工具平台和程序库
社区管理员
  • 工具平台和程序库社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧