RiccardoPepe
RiccardoPepe

Reputation: 5

created thread doesn't get executed

here I come again with a new question for this (blasted) threads programming. Here is my code, hope you can help me understand what's wrong with it (keep in mind I had to write this code again, not copy-paste, so there may be some type errors - the compiled code is ok and works, so the problem is not the syntax).

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

int i=0;

void *TFun(void *TArg)
{
printf("THREAD    i=%d\n", i);
i++;
return NULL;
}

int main()
{
pthread_t TID;

TID=pthread_create(&TID, NULL, TFun, NULL);
pthread_join(TID, NULL);

printf("THREAD    i=%d\n", i);
i++;

exit(0);
}

I expect this to print "THREAD i=0" and then "MAIN i=1", but this doesn't happen. it only prints "MAIN i=0", the Thread is not executed.

https://i.ibb.co/Y0KYWCK/code.png https://i.ibb.co/pznZ3TT/result.png

Upvotes: 0

Views: 30

Answers (1)

Milag
Milag

Reputation: 1996

The value of TID is normally written by reference within pthread_create(), but was also being overwritten with the int return value; change to an added int variable:

(old)

TID=pthread_create(&TID, NULL, TFun, NULL);

(new)

int pcr;
pcr = pthread_create(&TID, NULL, TFun, NULL);

Upvotes: 2

Related Questions