Data sharing in POSIX thread?
- From: "Jack" <junw2000@xxxxxxxxx>
- Date: 29 Aug 2006 11:57:34 -0700
How is data shared in POSIX thread? Below is a sample code:
#include <pthread.h>
#include <stdio.h>
#include <assert.h>
pthread_mutex_t cntr_mutex = PTHREAD_MUTEX_INITIALIZER;
long protVariable = 0L;//LINE1
void *myThread( void *arg )
{
int i, ret;
for (i = 0 ; i < 10000 ; i++) {
ret = pthread_mutex_lock( &cntr_mutex );
assert( ret == 0 );
protVariable++;
ret = pthread_mutex_unlock( &cntr_mutex );
assert( ret == 0 );
}
char *p;
p = malloc(1000); //LINE2
pthread_exit( NULL );
}
#define MAX_THREADS 10
int main()
{
int ret, i;
pthread_t threadIds[MAX_THREADS];
for (i = 0 ; i < MAX_THREADS ; i++) {
ret = pthread_create( &threadIds[i], NULL, myThread, NULL );
if (ret != 0) {
printf( "Error creating thread %d\n", (int)threadIds[i] );
}
}
for (i = 0 ; i < MAX_THREADS ; i++) {
ret = pthread_join( threadIds[i], NULL );
if (ret != 0) {
printf( "Error joining thread %d\n", (int)threadIds[i] );
}
}
printf( "The protected variable value is %ld\n", protVariable );
ret = pthread_mutex_destroy( &cntr_mutex );
if (ret != 0) {
printf( "Couldn't destroy the mutex\n");
}
return 0;
}
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? 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.
Thanks.
Jack
.
- Follow-Ups:
- Re: Data sharing in POSIX thread?
- From: David Schwartz
- Re: Data sharing in POSIX thread?
- Prev by Date: Re: accessing files, devices, in kernel modules
- Next by Date: Re: POSIX thread question
- Previous by thread: Max Thread per process.
- Next by thread: Re: Data sharing in POSIX thread?
- Index(es):
Relevant Pages
|