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

static void *worker_thread(void *arg) {
    /* Convert pointer back to an integer type of matching width */
    intptr_t input = (intptr_t)arg;

    printf("[Thread] Received argument: %ld\n", (long)input);

    /* Compute a result and return it via the void* return value */
    intptr_t result = input * input;

    /* Avoid returning pointers to local stack variables; passing an integer
       cast to intptr_t -> void* is safe and avoids heap allocation here. */
    return (void *)result;
}

int main(void) {
    pthread_t tid;
    intptr_t value_to_pass = 7;
    void *raw_ret = NULL;

    printf("[Parent] Creating thread with argument: %ld\n", (long)value_to_pass);

    int rc = pthread_create(&tid, NULL, worker_thread, (void *)value_to_pass);
    if (rc != 0) {
        fprintf(stderr, "pthread_create failed (code %d)\n", rc);
        return EXIT_FAILURE;
    }

    /* Block until the child thread finishes and capture its return pointer */
    rc = pthread_join(tid, &raw_ret);
    if (rc != 0) {
        fprintf(stderr, "pthread_join failed (code %d)\n", rc);
        return EXIT_FAILURE;
    }

    intptr_t exit_value = (intptr_t)raw_ret;
    printf("[Parent] Thread finished with return value: %ld\n", (long)exit_value);

    return EXIT_SUCCESS;
}