JubileeTheBear
JubileeTheBear

Reputation: 52

Run C Function in Separate Threads with Local Global Variables

I have some C source code that calls functions which modify global values. I would like to be able to run multiple, somewhat independent instances of the main code without sharing the global variables attached to the functions that are called. The main code is in a separate source file than the function definitions and the global variables, so the main function does not have direct access to the global variables. Is there a way to have multiple instances of the main code which calls functions with their own copies of global variables?

I've looked at threads, but the global variables will be shared between the threads. I've also looked at running two separate processes, and just use interprocess communication to communicate between the multiple instances, but that seems like too much work for what I want to do.

The optimal solution would be to have separate threads that each had their own copy of global variables that the functions use.

I was just wondering if anyone else had solved a similar problem through a simpler route.

EDIT: The functions with globals that I am calling are not my code, so I can't exactly modify the globals or the functions that call them.

Example code to help clarify the problem:

// In func.c

int g_A = 0;
void func()
{
    g_A++;
}


// In main.cpp

void Thread()
{
    while (true)
    {
        func();
    }
}

int main()
{
    // Could be threads, just looking for something that will allow 
    // me to run the "Thread" function in multiple parallel instances 
    // without sharing the global variables attached to the function 
    // that it calls
    std::thread foo1(func);
    std::thread foo2(func);
    foo1.join();
    return 0;
}

Upvotes: 0

Views: 1002

Answers (1)

paulsm4
paulsm4

Reputation: 121599

By definition, "globals" are global to the entire process.

It sounds like you're looking for something like Thread Local Storage. These variables are associated with an individual "thread".

You didn't mention your platform or your threading API, but here are a couple of links that might help:

Upvotes: 1

Related Questions