Re: Data sharing in POSIX thread?
- From: "Jack" <junw2000@xxxxxxxxx>
- Date: 31 Aug 2006 08:48:29 -0700
David Schwartz wrote:
Jack wrote:Does it means that if a thread allocate memory the thread must protect
My book says all the threads of the same process share the same data.
In the above code, 10 threads are created. Do they share all the
variables? For the global variable, protVariable, the 10 threads should
share it, it is understandable. How about the local variables i and ret
in
myThread()? Does each thread have its own copy of local variables or do
all the threads share the local variables?
Both. Each thread has its own copy of the local variables and each of
those are shared.
For example, if thread 1 and thread 2 each print out the address of the
"same" local variable, they will print different addresses. If they
somehow communicate those addresses to each other, each can access the
other's variable (assuming they are careful to do so during its
lifetime!).
If I allocate memory in
myThread() using malloc as LINE2, do all the threads share the same
allocated memory? I can not find the answers from my book.
If each thread calls 'malloc', then each thread allocates memory. Those
blocks of memory are fully shared and nothing stops one thread from
accessing the memory another thread allocated.
the allocated memory. Otherwise all threads can access it and the
result is unpredictable.
How to tell whether a stack is shared or not?
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).
Thanks.
.
- Follow-Ups:
- Re: Data sharing in POSIX thread?
- From: David Schwartz
- Re: Data sharing in POSIX thread?
- References:
- Data sharing in POSIX thread?
- From: Jack
- Re: Data sharing in POSIX thread?
- From: David Schwartz
- Data sharing in POSIX thread?
- Prev by Date: Re: how to get physical memory address from virtual memory address
- Next by Date: fdisk and mkfs tools
- Previous by thread: Re: Data sharing in POSIX thread?
- Next by thread: Re: Data sharing in POSIX thread?
- Index(es):
Relevant Pages
|