Hi all. I'm new to this forum.
I've some problem with this piece of code:
Code:
#define N 2
void* handler_function(void* args) {
int index = *((int*)args);
printf("\n-----index = %d------\n",index);
return NULL;
}
int main() {
pthread_t threads[N*N];
int i;
for (i=0;i<N*N;i++)
pthread_create(&(threads[i]),NULL,&handler_function,&i);
for (i=0;i<N*N;i++)
pthread_join(threads[i],NULL);
}
try to compile&exec it (i use posix thread so add -lpthread option to gcc command)
my output:
Code:
np2k@serena:~/source/thread$ gcc -o test test.c -lpthread
np2k@serena:~/source/thread$ ./test
-----index = 2------
-----index = 2------
-----index = 0------
-----index = 0------
np2k@serena:~/source/thread$
the problem is with pthread_create function. in fact, when I print the index value in the thread_function routine, I don't see all the values of index (from 0 to N*N-1).
A tricky solution to this matter is to add a sleep(1) after pthread_create. By doing so, things work well. But I don't want to wait, obviously.
please help me