This is my main function, where NO_RECIEVERS = 3
. I am trying to differentiate between the writer and reader threads using the value of i
that i send.
int main() {
int status, i;
pthread_t tr[NO_RECIEVERS], tw[NO_SENDERS], bd;
i=1;
for(i=1; i<=NO_SENDERS; i++) {
pthread_create(&tw[i-1], NULL, writer, &i);
}
for(i=1; i<=NO_RECIEVERS; i++) {
printf("%d\n", i);
pthread_create(&tr[i-1], NULL, reader, &i);
}
pthread_create(&bd, NULL ,daemon_thread, NULL);
for(i=1; i<=NO_SENDERS; i++) {
pthread_join(tw[i-1], NULL);
}
for(i=1; i<=NO_RECIEVERS; i++) {
pthread_join(tr[i-1], NULL);
}
pthread_join(bd, NULL);
return 0;
}
My reader function is as follows
void* reader(void *val) {
int ret, fd, id;
struct mssg data;
id = *(int*)val;
printf("id: %d %d\n", id, *(int*)val);
while(1) {
But this function seems to be creating threads with id some random values.. i get a log like this
...
id: 1 1
...
id: 2 2
...
id: 1 1
Next time i get.. its kind of random
...
id: 1 1
...
2
id: 2 2
...
id: 4 4
But the values i am assigning are limited to 1,2,3
You passed
&i
to all the threads you created... so each one has a pointer toi
, and when they dereference that to read the value ofi
, and what they read is whateveri
happens to be at the time.If you want to pass the value of
i
at the time of thepthread_create
, I suggestmalloc()
a small piece of memory, copyi
to it and pass the malloced thing to the thread (which can read it and thefree()
the memory. Or any other method that provides a copy ofi
in a different location for each thread created.