Shawn Huang Shawn Huang - 1 month ago 9
C Question

My loop doesnt run properly in multi-threading

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]
    to
    pthread_t t
    and create twice, is it possible to call pthread_join twice?



Thanks for your time reading my question.

alk alk
Answer

First add some more debug-logging:

int id;
for(i=0; i<2; i++)
{
    printf("i: %d\n",i);
    pthread_join(t[i], (void **)&id);
    printf("id[%d]: %d\n", i, id);
}

Re-run and memorize the output.

Then change it to look like this

int id;
for(i=0; i<2; i++)
{
    void * pv;   
    printf("i: %d\n",i);
    pthread_join(t[i], &pv);
    id = (intptr_t) pv;
    printf("id: %d\n", id);
}

Re-run and compare to the previous version.