多线程的问题
#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)