Antonio
Antonio

Reputation: 20296

Are function pointers thread safe?

(This follows Are static inline functions thread safe?)

Scenario: I have written a big piece of code, running on 2 parallel threads, which are identical in term of code and just process different data. I am seeing non-deterministic results. If I disable one of the 2 threads, the results become deterministic. Within this code I am using some function pointers, and I would like to understand if they could be a possible cause of my problem.

Are function pointers thread-safe in C? Said the other way around, if they have no static variable inside, but only some local variables and the input parameters, will a simultaneous call from the 2 threads cause unpredictable behaviour?

Example code:

void foo(int param1, int* out);
void bar(int param1, int* out);

typedef void (*fooBarFuncP_t)(int, int*);

static inline fooBarFuncP_t getFooBar(int selection) {
    switch (selection) {
        case 0:
            return &foo;
        case 1:
        default:
            return &bar;
    }
}

void test(int selection, int x, int* y) {
    (*getFooBar(selection))(x,y);
}

Where:

Is this thread-safe? If not, what solutions exist for this problem?

Upvotes: 2

Views: 2798

Answers (2)

Lundin
Lundin

Reputation: 214395

There is no difference between function pointers and regular variables in terms of thread-safety. If a variable is shared by several threads and at least on thread writes to the variable, you need to protect it.

Where a function is called from has no relevance for that function's thread-safety. The only thing that matters is which thread that executes the function. If several threads call the same function, no matter how they do it, then that function needs to be thread-safe.

Upvotes: 0

P.P
P.P

Reputation: 121407

Calling/using function pointer is no different to a using a function with respect to thread-safety. In the example, you posted there's no thread-safety issues (under the conditions you have stated).

Assuming you still have problems related to thread-safety, some suggestions:

  • Check if there's any data race in your code.

  • Check if there are any static variables involved through headers, library functions, third-party functions etc (I know you have said none but still it's possible you missed some).

  • Run your code under Helgrind.

Upvotes: 2

Related Questions