开发者

Boost::Thread or fork() : Multithreaded HTTP Proxy

I'm testing boost::thread on a system. It happens that I needed to act as a fork(), because one thread modifies the other variables, even member variables of class

I do the project using fork() or is there some alternative still using boost::thread?

开发者_如何学JAVA

Basically I run this program in Linux and maybe FreeBSD.

It is an http proxy,accept() in main thread, and a function that accepts a class (where there is the file descriptor socket) in a secondary thread that makes the service.

Is there a better way to implement a proxy?


fork() spawns a process which have independent memory regions. Changed must be mediate through IPC.

boost::thread create a thread which can share memory.

They are not comparable.


To create thread-local storage, use boost::thread_specific_ptr.

See http://www.boost.org/doc/libs/1_42_0/doc/html/thread/thread_local_storage.html.

(You may also decorate a global variable as __thread int xyz; to make it thread-local, if the compiler and architecture can support it.)


It sounds like you are trying to allow multiple threads to alter global variables without each others' changes affecting any of the other threads. By forking, the entire memory space of your application is basically copied and each branch of the fork has its own variables and the two branches cannot communicate except through IPC.

If you want to use boost::thread, you'll have to do this copying yourself if you don't want threads to affect each other since the same memory space is common among all threads. You could just create the variables local to each thread function.

Using threads instead of forking will be much more flexible especially when you want to start letting the threads share data. If you want to have variables that all of the threads can change, they should be protected by mutex locks when being changed so that only one thread can change a variable at one time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜