• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 230
  • Last Modified:

Pointers to functions and concurrency

I want to confirm my suspicion (I am working under RH 7.3):

I have a struct of type SomeType that has as a member a pointer to a function F (stateless function)

I can do the following:

SomeType ST1;

SomeType ST2;

// initialization code, etc

call to function F through ST1
call to function F through ST2

without worrying about ST1 and ST2 accessing the function. But what about if ST1 and ST2 were in different threads (LWP)?

Do I need to add protection to those calls?

  • 2
1 Solution
It depends.  Are all the variables used in F on the stack?
That is if you have a function F

int F(some params)
int x, int y; //stack variables
//do something
return x+y; //or something

then you are ok.
but if the function F uses static variables in it or globals then you probably need protection.

You may also need to ask yourself what is the relationship between ST1 and ST2.  if in the usage of ST1 can modify ST2 then you need to be careful (protection) whenever you use them.

for example

say struct Foo looks like this

struct Foo{
struct Foo * next;

and you do this

Foo *ST1, *ST2;
ST1 = (Foo*) malloc(sizeof(Foo));
ST2 = (Foo*) malloc(sizeof(Foo));
ST1->next = ST2;

then you had better be real careful (READ protection) if you ever enter areas where you may modify ST1->next while using ST2 at the same time.

I hope I at least gave you some ideas on what questions to ask when trying to make your decision.

Note: this advice is applicable if you are using a function that is a member or not.  I am not really sure what having as a member of your struct a pointer to a function makes it any different or special.

anyway hope that helps.

bichitoAuthor Commented:
You are right.

This will boil down to to implementation of pthreads and it is not dependent on C itself.

All my variables are in the stack or are parameters. These "should" be thread specific.

I will need to dig into pthreads to verify this.

How do I award the points?
bichitoAuthor Commented:
FYI, if anybody has the same doubt:

The pthreads specs specifies a stack per thread.

So as long as the variables in the function pointed to are in the stack there is no need for protection

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now