Retired account
Retired account

Reputation: 103

Understanding behavior of program

I'm running the following program:

#include <unistd.h>
#include<time.h>
static void threadStart(void (*function)(void), void* arg) {
    // schedules thread in Queue
    function(void* arg);
}

The compiler giving me two errors:

In function ‘threadStart’:
sample.c:5:11: error: expected expression before ‘void’
 function(void* arg);
       ^
 sample.c:5:11: error: too many arguments to function ‘function’

How pass a function to run with a given argument without raising errors?

Upvotes: 0

Views: 54

Answers (1)

selbie
selbie

Reputation: 104579

I had started to write-up an answer, that I just deleted that suggested this is what you wanted:

static void threadStart(void (*function)(void*), void* arg) {
    // schedules thread in Queue
    function(arg);
}

But then I looked at what you are trying to do with a function pointer, that nearly resembles a pthread_create start routine.

So it didn't make sense that you've got a function called threadStart that neither starts a thread nor appears to be the start routine for a thread. I could be wrong, because we don't see anything else in your code that suggests how threadStart is invoked.

So I was wondering if this is what you really meant, a function to be run within a thread:

void* threadStart(void* arg)
{
    someOtherCodeOrFunction(arg); // your code goes here
}

And you meant to instantiate that thread to run that above function with arg as the parameter value:

pthread_create(&thread, NULL, threadStart, arg);

Upvotes: 1

Related Questions