Reputation: 551
I always learnt, that shared memory is the fastest way to share data between two threads (like e.g. http://www.boost.org/doc/libs/1_55_0/doc/html/interprocess.html). However, today I discovered that using boost::ref(X)
it is possible to give boost
a reference to X
enabling access to X
from outside the thread. Therefore the following pseudocode should work:
MyObjext X(para1,para2); // MyObject has a () operator
boost::thread thr(boost::ref(X));
X.setSomeMember(1);
This got me thinking: Assuming setSomeMember
is thread safe, then - for most applications - this approach seems much easier, since most applications spawn their threads as they need and thus can always save and access the object X
. So, why would I use shared memory or message queues anyway, if I have access to the thread object directly? Is it maybe faster? Or am I missing something here?
Upvotes: 3
Views: 919
Reputation: 393354
They're just different features - you happen to highlight the similarities.
Yes, threads are more lightweight than processes.
What you lose is isolation (processes can only share what's explicitely exposed, and only given the right permissions). There is no such control for inter-thread sharing.
If one thread messes up the shared state, all threads die, the same goes for shared memory. However, if one thread dies, the whole process dies, which doesn't happen for separate processes.
All in all, it's different. Inter-process synchronization/sharing is more heavy weight but has more features (how will you run a separate thread on a different host :)).
Upvotes: 4