0

I'm working on a project that is supposed to create a couple of threads, each of which call a function that prints a message when the thread has finished executing.

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

void* match(int id, int number){
    for(;;){
        int random = 1 + (rand()%9999);
        if(random == number) break;
    }
    printf("Thread number %d has completed.", id);
}

int main (int argc, char *argv[]){
    int conv = atoi(argv[1]);
    pthread_t th[10];
    int i;
    for (i = 0; i < 10; i++){
        if(pthread_create(th+i, NULL, &match(i, conv), NULL)!=0){
        perror("Failed to create thread");
        return 1;
    }
    for (i = 0; i < 10; i++){
        if (pthread_join(th[i], NULL)!= 0){
            return 2;
        }
    }
    return 0;
}

The problem is that trying to pass arguments to the function pointer gives me an error "lvalue required as unary '&' operand". It looks like pthread_create only accept a function pointer with a specific signature for its third argument. What do I need to change to make this work?

  • 1
    "*It looks like pthread_create only accept a function pointer with a specific signature for its third argument.*" -- yes, exactly right. The thread-entry function accepts a pointer to `void` as its only argument. This is sufficient to provide (a pointer to) any object of any type, including compound types such as structures and arrays, which is sufficient to provide arbitrary data. – John Bollinger Sep 30 '22 at 19:41
  • As for the error you report, `&match(i, conv)` is trying to obtain the address of the *return value* of a function call (which is not well defined). It is not taking the address of the function itself. – John Bollinger Sep 30 '22 at 19:44

0 Answers0