Phạm Ân
Phạm Ân

Reputation: 175

How to reduce dependence caused by global variables in c program

I want to speed up the processing of a sequential C program using multi-threading. My problem is that my C program has a lot of global variables. They are read and written by the functions in my C program. Therefore, it is prevented to parallelize functions together by multithreading because it no longer holds the exact result compared to running sequence programs.

I using OpenMP to handle my C program. However, I wanna refactor my C program to react above purpose before use OpenMP

Here my example:

int a = 5 ; // global variable

funcA () {
    int b; 
    b = a + 5; // read a
}

funcB () {
    printf("%d\n", a); 
}

I don't wanna find the way to parallel complete funcA and funcB but I want reduce the dependency caused global variable (like variable a in above example).

Upvotes: 2

Views: 624

Answers (2)

Rishikesh Raje
Rishikesh Raje

Reputation: 8614

In general it is not an easy task to remove global variables.

You need to go on a case by case basis.

What you really need to do is to try to pass the variables required as function parameters rather than having them as globals.

In this example given, i cannot give any solution without looking at how the functions funcA and funcB are called. You should try to pass the variable a as a parameter to both the functions. You may need to go back up a few functions until you get to a common function which ultimately calls both functions.

Upvotes: 1

virolino
virolino

Reputation: 2227

There is no simple way to do a complicated thing. It can seem difficult sometimes to design a code without global variables even when coding from zero. I your case, the problem is significantly more difficult.

There is not (and cannot be) a generic solution about how to minimize the number of global variables.

The only thing which can be done is:

  • analyze the code base;
  • understand the purpose of the global variables and how they are used;
  • find a way to achieve the same behavior without using global variables.

Of course, it might be easier for some global variables to be dealt with than others. You may want to start with the former. Seeing success coming your way will help your morale during the task.

It might help you if you read about how to make code:

  • tread safe;
  • re-entrant.

Google can help you greatly on this.

Upvotes: 1

Related Questions