0

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?

2
  • what do you mean by cascade? Commented Jun 9, 2020 at 9:20
  • 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. Commented Jun 9, 2020 at 9:23

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

1 Comment

And obviously you can't have 2 threads with same callback accessing the same data, unless you have some means of thread-safety protection inside the callback.

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.