开发者

C/C++: duplicate main() loop in many threads

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 variabl开发者_JAVA百科es, so each thread has its own set ? (somekind of thread local storage, but without affecting doSomething()).. I use VisualC++


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.


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.


Your best bet is thread local storage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜