Search code examples
cmultithreadingglobal-variables

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).


Solution

  • 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.