Re: Data sharing in POSIX thread?




Jack wrote:

Does it means that if a thread allocate memory the thread must protect
the allocated memory. Otherwise all threads can access it and the
result is unpredictable.

No. Threads are not at war with each other. They're more like members
of a well-functioning household. You don't have to lock your bedroom
door because nobody is going to steal your sheets. If someone is, the
fix is to make them stop, not to lock the door.

No, if we *want* another thread to be able to access that memory
safely, we may need to use a synchronization mechanism like a lock. But
that's much like the lock on the bathroom door. It's not to keep evil
people out, it's to let good people know that they must wait to use the
bathroom if they want to keep the efficient cooperation working.

This is a *very* important concept to understand. Questions like "does
each thread have its own stack or are the stacks shared" try to
pigeon-hole into two possibilities and ignore the third possibility --
each thread does have its own stack (that is, there is one stack per
thread) but they are also shared (that is, each thread can access
another thread's stack should it be coded to do so or do so through a
bug).

How to tell whether a stack is shared or not?

It's not clear precisely what you're asking. Stacks are always shared
in the sense that one thread can access another thread's stack if it is
coded to do so (or somehow does so erroneously due to a bug). They are
also never shared in the sense that each thread has its own stack to
work from. This is always the case with POSIX threading, so there is
nothing to check on. (Although theoretically threads could trade stacks
or you could have more stacks than threads and 'pick up' a new stack,
this is rarely done and only when you know exactly what you're doing
and why.)

DS

.


Quantcast