I am studing mutithread programing in C, and meet a difficuty.
The source code is:
Code:
#include <string.h>
#include <pthread.h>
#define N 26
void disp(void *str);
int main(void)
{
int i;
char *chp;
chp = (char*)malloc(sizeof(char) * N);
for(i=0; i<N; *(chp+i)='a'+i++);
pthread_t *thread;
thread = (pthread_t*)malloc(sizeof(pthread_t) * N);
for(i=0; i<N; ++i)pthread_create(thread+i, 0, (void*)&disp, (void*)(chp+i));
sleep(1);
putchar('\n');
return 0;
}
void disp(void *str)
{
char *strtemp;
strtemp = (char*)str;
putchar(*strtemp);
}
As you see, I use a word "sleep(1);" in the 20th line.
If I didn't use this, it can't work well.
What's the problem with my code, and why I must use the "sleep(1)" ?
Please help me.