0
votes

I have this code as a practice but I couldn't find a clear way to solve it and we have to stick to this format

#include <stdio.h>

#include <pthread.h>

#define x 2

pthread_t arr[x];

int arr2[2][2] = {{1,1},{2,2}};

void* func(void* arg[][]){

//print thread id

//each thread will print one row of the 2d array (arr2)

}

int main(){

    pthread_attr_t attr;

    pthread_attr_init(&attr);

            // create the threads

    int i,k;

    for(i=0; i<2 ;i++){

            k=pthread_create(&arr [i] , &attr, func, //fill here );

    }

            // join the threads



            return 0;



}

first I had this error

main.c:12:18: error: array type has incomplete element type ‘void *[]’

void* func(void* arg[][]){

then I solved it using

void* func(void* arg[2][2]){

then a cascading problem raised,

 k=pthread_create(&arr [i] , &attr, func, (void*)arr2 );

main.c:25:37: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-poin

ter-types]

/usr/include/pthread.h:244:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(void * (*)

[2])’

how to cascade 2d int array to 2d void pointer array?

and how to print the thread id of 2d array argument?

1
what do you mean by cascade? - Cristi
And what do you even need the void* arg[][] for? You can't use that as parameter to pthreads callback, the function format is fixed void* f (void*), it is not for you to decide. - Lundin

1 Answers

0
votes

You can't re-define the callback function format used by pthreads, it's not for the programmer to decide. You must use void* func (void* arg), period.

And if you ever find yourself casting something to void* in C, you most likely have a bug, or maybe you are using a C++ compiler.

Simply do this:

void* func (void* arg)
{
  int (*arr)[2] = arg;
  ...
  arr[i][j] = whatever;

...

result = pthread_create(&arr[i], &attr, func, arr2);