开发者

boost::thread function execution

开发者 https://www.devze.com 2023-02-24 17:23 出处:网络
How do I use a boost::thread to execute a function with each thread executing in its own memory space. So that when I allocate a new variable with in the function it only lives as an instance in the e

How do I use a boost::thread to execute a function with each thread executing in its own memory space. So that when I allocate a new variable with in the function it only lives as an instance in the executing thread.

Just to clarify I want to spawn threads that execut开发者_运维问答e the same method using boost::thread but I do not want to use locks or semaphores I just want it to execute in a separate space.


Anything you allocate inside the thread function is already local to that function, as long as they're not declared as static. Just write your code as normal (avoiding static local variables) and you'll be fine.


If you need to create a thread that is running completely within its own address space, then what you are looking to do is to create a process, not a thread. Threads by definition are points of execution running within the same address space of the parent process.

If you really need to create threads (i.e. there's still memory and other resources shared between threads), but you also need to have a portion of memory dedicated to a specific thread, then you have few options: 1) as ildjarn suggested, have thread procedure allocate local (or dynamic memory) and write your code so that each thread uses this memory that it allocates for itself 2) Take a look at TLS (Thread Local Storage). It is an API that allows you to create "global" variables which are dedicated to a specific thread. Also some variations of C++ have built-in keywords for declaring variables which use TLS under the hood.

Note that in above options you will not get automatic isolation where a thread would not be able to corrupt another threads memory. The only way to get this isolation is to spawn multiple processes (or switch to one of .NET languages and instantiate multiple AppDomains running within the same process).

0

精彩评论

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

关注公众号