views:

84

answers:

3

I have this "interesting" problem. I have this legacy code that looks like

int main()
{
  while(true) {
    doSomething();
 }
}

I would like to duplicate that doSomething() in many threads, so that now main() would look like

int main() {
  runManyThreads(threadEntry)
}

void threadEntry() {
   while(true) {
    doSomething();
  }
}

The problem is that doSomething() access many global and static variables, and I cannot alter its code. Is there a trick to duplicate those static variables, so each thread has its own set ? (somekind of thread local storage, but without affecting doSomething()).. I use VisualC++

+1  A: 

Untested, but I think you can do something like:

#define threadlocal __declspec(thread)

And then put threadlocal before all the variables that should be local to the thread. Might not work though, it's generally not a good idea to just throw functions into threads when they weren't written to be multi-threaded.

GMan
I'm with Jerry on this not being a reasonable option.
Steven Sudit
@Steven: I am too. :)
GMan
As usual, I appreciate your candor.
Steven Sudit
+4  A: 

To make a long story short, no, at least not (what I'd call) reasonably.

Under the circumstance of not wanting to change doSomething(), your best bet is probably to run a number of copies of the existing process instead of attempting to use multi-threading. If each thread is going to use a separate copy of global variables and such anyway, the difference between multithreading and multiple processes will be fairly minor in any case.

Jerry Coffin
A: 

Your best bet is thread local storage.

Nikolai N Fetissov