分段错误pthread_join因为pthread_t id更改为0

时间:2015-09-16 21:30:59

标签: c multithreading segmentation-fault pthreads pthread-join

我正在用pthread编写一个C程序。在我开始我的线程并执行它们之后,某些东西会在后台将我的两个pthread之一的值更改为0 ,这是我无法解释的原因。 在我的机器上,这个问题已经发生在

之间
QState

printf( "Created thread %d !\n", id2 );

这是C代码:

printf( "id2==%d !\n", id2 );

我的锁定和解锁功能如下所示:

#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 );
}

为什么我的pthread ID会突然改变?

0 个答案:

没有答案