I am writing a C program with pthread. After I start my threads and execute them, something changes the value of one of my two pthreads to 0 in the background for a not explainable reason for me. On my machine, this problem already occurs between
printf( "Created thread %d !\n", id2 );
and
printf( "id2==%d !\n", id2 );
Here is the C code:
#include "mutex.h"
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_t id1;
pthread_t id2;
unsigned char mutex = 0;
void* run( )
{
pthread_t s=pthread_self();
printf( "Thread(%d) starting.\n", s );
mutex_lock( &mutex );
printf( "Working in the critical area for 2s.\n" );
sleep( 2 );
mutex_unlock( &mutex );
s=pthread_self();
printf( "Thread(%d) exiting.\n", s );
pthread_exit( NULL );
}
int main()
{
if( pthread_create( &id1, NULL, run, NULL ) )
{
perror( "pthread_create failed!" );
exit( EXIT_FAILURE );
}
printf( "Created thread %d !\n", id1 );
if( pthread_create( &id2, NULL, run, NULL ) )
{
perror( "pthread_create failed!" );
exit( EXIT_FAILURE );
}
printf( "Created thread %d !\n", id2 );
int r=0;
printf( "Ready for joining thread %d !\n", id1 );
printf( "id2==%d !\n", id2 );
if( ( r=pthread_join( id1, NULL ) ) )
{
fprintf( stderr, "%d==pthread_join( id1, ... ) failed!\n", r );
exit( EXIT_FAILURE );
}
printf( "Ready for joining thread %d !\n", id2 );
if( ( r=pthread_join( id2, NULL ) ) )
{
fprintf( stderr, "%d==pthread_join( id2, ... ) failed!\n", r );
exit( EXIT_FAILURE );
}
exit( EXIT_SUCCESS );
}
My functions lock and unlock look like this:
void mutex_lock( unsigned char* m )
{
printf( "mutex_lock()\n" );
while( tsl( m )==1 );
printf( "mutex locked\n" );
}
void mutex_unlock( unsigned char* m )
{
printf( "mutex_unlock()\n" );
*m=0;
printf( "mutex unlocked\n" );
}
Why does my pthread ID suddenly change?