linux下多线程的问题
刚刚接触linux下的多线程,有这样一个问题:
在线程函数里实现一个生成字符串的功能,然后主线程里还要使用子线程里生成的这个字符串。我现在的做法如下
void* thr_fn( void* arg )
{
char* newStr = 0;
if ( !arg )
{
newStr = (char*)malloc(1);
newStr[0] = '\0';
}
else
{
newStr = (char*)malloc( strlen( (char*)arg + 10 ) );
strcpy( newStr, "http://" );
strcat( newStr, (char*)arg );
}
pthread_exit( (void*)newStr ); // line A
}
int main()
{
pthread_t tid;
char str[] = "www.sina.com";
int err = pthread_create( &tid, NULL, thr_fn, str );
if ( err != 0 )
{
printf("can't create thread: %s\n", strerror(err) );
exit(1);
}
void* ret;
pthread_join( tid, &ret );
printf( "newStr = %s\n", (char*)ret ); // line B
free(ret);
return 0;
}
运行结果如下:
newStr = http://www.si-
我看了一下在line A和line B处的内存:
newStr = 0xb7500468
0xb7500468: 68 74 74 70 3a 2f 2f 77|77 77 2e 73 69 6e 61 2e http://www.sina.
0xb7500478: 63 6f 6d 00 00 00 00 00|00 00 00 00 00 00 00 00 com.............
此时看一下正常
在line B处观察时,发现
ret = 0xb7500468
0xb7500468: 68 74 74 70 3a 2f 2f 77|77 77 2e 73 2d 00 00 00 http://www.s-...
0xb7500478: 2f 6c 69 62 2f 69 33 38|36 2d 6c 69 6e 75 78 2d /lib/i386-linux-
明显这段被改了。
请问这是为什么?
[解决办法]
线程的执行顺序是不确定的,得加上同步
[解决办法]
newStr = (char*)malloc( strlen( (char*)arg + 10 ) );
括号打错了