pthread argument's value changed

2019-09-16 19:18发布

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

1条回答
混吃等死
2楼-- · 2019-09-16 19:59

You passed &i to all the threads you created... so each one has a pointer to i, and when they dereference that to read the value of i, and what they read is whatever i happens to be at the time.

If you want to pass the value of i at the time of the pthread_create, I suggest malloc() a small piece of memory, copy i to it and pass the malloced thing to the thread (which can read it and the free() the memory. Or any other method that provides a copy of i in a different location for each thread created.

查看更多
登录 后发表回答