Data sharing in POSIX thread?



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

.



Relevant Pages

  • Re: Data sharing in POSIX thread
    ... How about the local variables i and ret ... myThread() using malloc as LINE2, do all the threads share the same ... For global variables, the addresses of global variables are the same ...
    (comp.unix.programmer)
  • POSIX thread question
    ... int i, ret; ... mainand myThread(), or just myThread? ...
    (comp.os.linux.development.system)
  • Data sharing in POSIX thread
    ... void *myThread(void *arg) ... int i, ret; ... Does each thread have its own copy of local variables or do ...
    (comp.unix.programmer)
  • Re: [Winbond] flash memory reader SCSI device drivers [C sources]
    ... static inline int wbms_send_tpc(unsigned char cmd, unsigned char *buffer, ... unsigned int ret; ... goto lab_out; ... unsigned int block_address, ...
    (Linux-Kernel)
  • Re: Linux 2.6.29.4
    ... static int is_efer_nx ... if (ret) ... struct ftdi_private { ... the specific security attributes of the socket ...
    (Linux-Kernel)