I've got a simple pthread example. When I run the executable I get a different number of threads running each time when I assumed I should be always generating and running 5 threads.
My compile statement:
Code:
$ gcc -Wall ptdetached.c -o runmain -pthread
Here is a sample of the last few runs:
Code:
$ ./runmain
Thread 296150784 started
Thread 296150784 has detached and will end on it's own
Thread 279365376 started
Thread 279365376 has detached and will end on it's own
Thread 287758080 started
Thread 287758080 has detached and will end on it's own
Thread 262579968 started
Thread 262579968 has detached and will end on it's own
Thread 270972672 started
Thread 270972672 has detached and will end on it's own
$ ./runmain
Thread -100919552 started
Thread -100919552 has detached and will end on it's own
$ ./runmain
Thread 1415571200 started
Thread 1415571200 has detached and will end on it's own
$ ./runmain
Thread 469026560 started
Thread 469026560 has detached and will end on it's own
$ ./runmain
Thread -1016367360 started
Thread -1016367360 has detached and will end on it's own
Code:
#include <pthread.h>
#include <stdio.h>
//GLOBALS
#define MAX_THREADS 5
void *threadWorker( void *arg )
{
//LOCALS
int ret;
printf( "Thread %d started\n" , (int)pthread_self() );
ret = pthread_detach( pthread_self() );
if ( ret != 0 ){
printf( "error detaching pthread %d\n", (int)pthread_self() );
}
else{ printf( "Thread %d has detached and will end on it's own\n" , (int)pthread_self() ); }
pthread_exit( arg );
}
int main()
{
//LOCALS
int ret, i, status;
pthread_t threadIds[MAX_THREADS];
for (i=0; i < MAX_THREADS ; i++)
{
ret = pthread_create( &threadIds[i], NULL, threadWorker, (void *)i );
if (ret != 0)
{
printf( "error creating thread %d\n" , (int)threadIds[i] );
}
}
return 0;
}