-1

My code is not working... But another example that is similar to my code is working. How can I fix?

It seems like pthread_join() is internally change integer value like my code. But mine does not work.

Can anybody help me to fix?

#include <stdio.h>

void test(void **temp) {
    int foo = 3;
    *temp = foo;
}

int main(void) {
    int temp;

    test((void **)&temp);
    printf("%d\n", temp);

    return 0;
}

pthread_join example:

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

void *test(void *data) {
    int i;
    int a = *(int *)data;
    for (i = 0; i < 10; i++) {
        printf("%d\n", i * a);
    }
}

int main() {
    int a = 100;
    pthread_t thread_t;
    int status;

    if (pthread_create(&thread_t, NULL, test, (void *)&a) < 0) {
        perror("thread create error:");
        exit(0);
    }

    pthread_join(thread_t, (void **)&status);
    printf("Thread End %d\n", status);
    return 1;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189

2 Answers2

1

But mine does not work..

This statement:

pthread_join(thread_t, (void **)&status);

assigns to status the return value of your thread function. But your function doesn't return anything, so you get garbage.

To fix this, make your test function return something.

P.S. Please do turn on compiler warnings (-Wall, -Wextra) -- the compiler should have warned you of the bug already.

P.P.S Please do not name your variables like this: thread_t -- the _t stands for type, and thead_t is not a type.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
0

You are trying to make temp into two void pointers (void**) when you actually only have one pointer to the int temp. Just return the pointer value and you can use this in a similar pthread example.

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

void *test(void *temp) {
    int *ptr = (int*)malloc(sizeof(int));
    *ptr = 3;
    return ptr;
}

int main(int argc, char *argv[]) {
    int *temp = (int*)test(nullptr);
    printf("%d\n", *temp);
    free(temp);
    return 0;
}