1

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?

Mao
  • 56
  • 1
  • 6
  • You'll need to provide *all* relevant code. What is `tsl()` doing? Also, why do you assume `pthread_t` is just an alias for `int`? – EOF Sep 16 '15 at 21:38
  • I don't assume it, I just print it that way. The second pthread_join gives me a ESRCH, so I simply output my variables. – Mao Sep 16 '15 at 21:44
  • tsl is source i didn't write myself, I only have an object file for this. It is a function doing "Test and Set Lock". – Mao Sep 16 '15 at 21:45
  • 1
    Well, after replacing your mutex with a `pthread_mutex_t` and the corresponding initializers & functions, and fixing `void *run(void *)` to have the right prototype, the program works fine for me. **Cannot reproduce** – EOF Sep 16 '15 at 21:50
  • Having reviewed the code, the only place the problem can be is on the line that calls `tsl(m)`. So either you aren't using the function correctly, or the function itself is broken. – user3386109 Sep 16 '15 at 21:56
  • Okay, thanks a lot! I was totally stuck and desperate. – Mao Sep 16 '15 at 22:23

0 Answers0