-1

I am currently working my way through threads in C, and I am currently stuck on using my one parameter (an array to be sorted) on thread creation as the array to work with. For an example:

void* sort(void* param)

How do I grab param so that it can be used as an int array local variable?

Also to return the sorted array would I just do return array on the last line,

and do something like int sorted_array[] = pthread_create(&tid, &attr, sort, &un_sorted_array) to capture it?

I'm new to C to any help would be appreciated? Using void pointer to an array The solution here still gave me an invalid initalizer error.

5
  • Possible duplicate of Concept of void pointer in C programming Commented Oct 12, 2015 at 0:21
  • I tried making sense of that link, but I'm still stuck. Commented Oct 12, 2015 at 0:32
  • For starters, you should post your entire code. Commented Oct 12, 2015 at 0:34
  • void* merge(void* arg) {int *arg_ptr[] = (int*) arg; int arr[] = *arg_ptr;} gives me an invaild initializer error Commented Oct 12, 2015 at 0:39
  • Try void* merge(void* arg) { int *arg_ptr = (int*) arg; }. To get the result you need to call pthread_join. Commented Oct 12, 2015 at 4:22

1 Answer 1

0

To access your array you can cast void pointer to int pointer like this

void* merge(void* arg) {
    int* a = (int*) arg;
}

To return array you simply do

return a;

where a is int*. And to get the result from main thread you call pthread_join with second argument that points to some int*.

pthread_join(tid, (void*)&b);

where b is int* b;.

To pass argument to thread you need to get address of the first element of the array (it is the same as pointer for this array). Do it like this

pthread_create(&tid, NULL, merge, (void*)&a[0]);

where a is an array int a[N];.

See full example for pthread with int array as argument and int* as return value.

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

#define N 10

void* merge(void* arg) {
    int* arr = (int*) arg;
    int* res = malloc(N * sizeof(int));
    for(int i = 0; i < N; ++i) {
            res[i] = arr[i] + 1;
    }
    return res;
}

int main() {
    pthread_t tid;

    int a[N];
    int* b;
    for(int i = 0; i < N; ++i) {
            a[i] = i;
    }

    printf("a = [");
    for(int i = 0; i < N; ++i) {
            printf("%3d ", a[i]);
    }
    printf("]\n");

    pthread_create(&tid, NULL, merge, (void*)&a[0]);
    pthread_join(tid, (void*)&b);

    printf("b = [");
    for(int i = 0; i < N; ++i) {
            printf("%3d ", b[i]);
    }
    printf("]\n");

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.