I try to write a multi-thread program, and meet some problems.
After I run main.c
, and I get
i: 0
new thread 0
new thread 1
i: 1
i: 1
//main.c
#include <pthread.h>
#include <stdio.h>
#include <stdint.h>
void* routine(void* arg)
{
int id = (intptr_t) arg;
printf("new thread %d\n", id);
pthread_exit((void*)(intptr_t) id);
}
int main()
{
pthread_t t[2];
int i;
for(i=0; i<2; i++)
{
int ret = pthread_create (&t[i], NULL, &routine, (void *)(intptr_t) i);
if(ret != 0) {
printf("Error: pthread_create() failed\n");
return -1;
}
}
int id;
/////////here
for(i=0; i<2; i++)
{
printf("i: %d\n",i);
pthread_join(t[i], (void **)&id);
}
/////////here
pthread_exit(NULL);
}
My problems are
- Why the last loop runs thrice?
- If I change
pthread_t t[2]
topthread_t t
and create twice, is it possible to call pthread_join twice?
Thanks for your time reading my question.