POSIX thread question
- From: "Jack" <junw2000@xxxxxxxxx>
- Date: 28 Aug 2006 14:15:21 -0700
Below is simple code of POSIX thread from a book:
#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 );
}
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;
}
It creates 10 threads. My questions are:
1. The 10 threads share the same code. Do the 10 threads share both
main() and myThread(), or just myThread()?
2. The 10 threads share the same variables. Do the 10 threads share all
the variables in the code? or only global variables?
3. The variable protVariable (LINE1) is shared among the 10 threads.
All the 10 threads can modify protVariable, right?
4. I use the following command to compile it:
gcc -o pt pthread.c
The link error is:
/tmp/cccuKYQv.o(.text+0xeb): In function `main':
: undefined reference to `pthread_create'
/tmp/cccuKYQv.o(.text+0x135): In function `main':
: undefined reference to `pthread_join'
collect2: ld returned 1 exit status
What is the problem?
Thanks.
.
- Follow-Ups:
- Re: POSIX thread question
- From: Mikko Rauhala
- Re: POSIX thread question
- Prev by Date: how to trap FPU
- Next by Date: Re: POSIX thread question
- Previous by thread: how to trap FPU
- Next by thread: Re: POSIX thread question
- Index(es):
Relevant Pages
|