1

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

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

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

这是C代码:

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

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

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

为什么我的 pthread ID 突然变了?

4

0 回答 0