-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.

atg
  • 127
  • 2
  • 13
  • Possible duplicate of [Concept of void pointer in C programming](http://stackoverflow.com/questions/692564/concept-of-void-pointer-in-c-programming) – Tim Biegeleisen Oct 12 '15 at 00:21
  • I tried making sense of that link, but I'm still stuck. – atg Oct 12 '15 at 00:32
  • For starters, you should post your entire code. – Tim Biegeleisen Oct 12 '15 at 00:34
  • `void* merge(void* arg) {int *arg_ptr[] = (int*) arg; int arr[] = *arg_ptr;}` gives me an invaild initializer error – atg Oct 12 '15 at 00:39
  • Try `void* merge(void* arg) { int *arg_ptr = (int*) arg; }`. To get the result you need to call [`pthread_join`](http://man7.org/linux/man-pages/man3/pthread_join.3.html). – Nikolay K Oct 12 '15 at 04:22

1 Answers1

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;
}
Nikolay K
  • 3,770
  • 3
  • 25
  • 37