多线程的问题

yphui18 2011-06-24 04:14:53
#include <stdio.h>
#include <malloc.h>
#include <stddef.h>
#include <stdlib.h>
#include <pthread.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define N 5
pthread_t ntid;
int nChildCount=0;
void printids(const char *s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid);
nChildCount--;
}
void *thr_fn(void *arg)
{
nChildCount++;
printids(arg); return NULL;
}
int main(int argc, char* argv[])
{
int i;
for(i=0;i<8;i++)
{
int err;
char strI[12];
//sprintf(strI,"the i is :%d,child thread ",i);如果这行程序加上去的话,只能创建一个线程,如果注释掉话,就可以创建八个线程.

err = pthread_create(&ntid, NULL, thr_fn, "");
pthread_join(ntid, NULL);
if (err != 0)
{
fprintf(stderr, "can't create thread: %s\n", strerror(err)); exit(1);
}
}
return 0;
}

int getx(int x,int y)
{
return x+y;
}



上面有一行程序
sprintf(strI,"the i is :%d,child thread ",i);如果这行程序加上去的话,只能创建一个线程,如果注释掉话,就可以创建八个线程.求高手解释一下

不注释掉的话情况,运行的结果是
pid 15654 tid 2 (0x2)

注释掉这行程序后运行的结果是
pid 19631 tid 2 (0x2)
pid 19631 tid 3 (0x3)
pid 19631 tid 4 (0x4)
pid 19631 tid 5 (0x5)
pid 19631 tid 6 (0x6)
pid 19631 tid 7 (0x7)
pid 19631 tid 8 (0x8)
pid 19631 tid 9 (0x9)
...全文
97 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
sdudubing 2011-06-24
  • 打赏
  • 举报
回复
也学习啦
luciferisnotsatan 2011-06-24
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 justkk 的回复:]

char strI[12];
//sprintf(strI,"the i is :%d,child thread ",i);如果这行程序加上去的话,只能创建一个线程,如果注释掉话,就可以创建八个线程.

内存越界了,strI长度只有12,你给它赋值这么长。。
[/Quote]
正解
pengzhixi 2011-06-24
  • 打赏
  • 举报
回复
[Quote=引用 6 楼 justkk 的回复:]
char strI[12];
//sprintf(strI,"the i is :%d,child thread ",i);如果这行程序加上去的话,只能创建一个线程,如果注释掉话,就可以创建八个线程.

内存越界了,strI长度只有12,你给它赋值这么长。。
[/Quote]

可以结贴了!
枫桦沐阳 2011-06-24
  • 打赏
  • 举报
回复
char strI[12];
sprintf(strI,"the i is :%d,child thread ",i);

the i is :%d,child thread 太长了,超过12了。。。额。
justkk 2011-06-24
  • 打赏
  • 举报
回复
char strI[12];
//sprintf(strI,"the i is :%d,child thread ",i);如果这行程序加上去的话,只能创建一个线程,如果注释掉话,就可以创建八个线程.

内存越界了,strI长度只有12,你给它赋值这么长。。
至善者善之敌 2011-06-24
  • 打赏
  • 举报
回复
//sprintf(strI,"the i is :%d,child thread ",i);如果这行程序加上去的话,只能创建一个线程,如果注释掉话,就可以创建八个线程.
感觉和这个没关系,多线程。。。。
c_losed 2011-06-24
  • 打赏
  • 举报
回复
debug调下 看是循环问题还是sprintf问题
TimZhuFaith 2011-06-24
  • 打赏
  • 举报
回复
线程退出了。。。?Sleep下看看
五哥 2011-06-24
  • 打赏
  • 举报
回复
学习 ,继续学习
就想叫yoko 2011-06-24
  • 打赏
  • 举报
回复
我认为不是此处的问题
可惜是windows无法帮你调~~

64,649

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

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