3

私は簡単なpthreadコードを書きました

#include <pthread.h>
#include <stdio.h>
#include <math.h>

#define ITERATIONS 500

// A shared mutex
pthread_mutex_t mutex;
int target;

void* opponent(void *arg)
{
  int i;
  printf("opp, before for target=%d\n", target);
  pthread_mutex_lock(&mutex);
  for(i = 0; i < ITERATIONS; ++i)
  {
    target++;
  }
  pthread_mutex_unlock(&mutex);
  printf("opp, after for target=%d\n", target);

  return NULL;
}

int main(int argc, char **argv)
{
  pthread_t other;

  target = 5;

  // Initialize the mutex
  if(pthread_mutex_init(&mutex, NULL))
  {
    printf("Unable to initialize a mutex\n");
    return -1;
  }

  if(pthread_create(&other, NULL, &opponent, NULL))
  {
    printf("Unable to spawn thread\n");
    return -1;
  }

  int i;
  printf("main, before for target=%d\n", target);
  pthread_mutex_lock(&mutex);
  for(i = 0; i < ITERATIONS; ++i)
  {
    target--;
  }
  pthread_mutex_unlock(&mutex);
  printf("main, after for target=%d\n", target);

  if(pthread_join(other, NULL))
  {
    printf("Could not join thread\n");
    return -1;
  }

  // Clean up the mutex
  pthread_mutex_destroy(&mutex);

  printf("Result: %d\n", target);

  return 0;
}

次に、このコマンドでコンパイルします

gcc -pedantic -Wall -o theaded_program pth.c -lpthread

ただし、プログラムを実行するたびに、異なる結果が得られます!!

 $ ./theaded_program
 main, before for target=5
 main, after for target=-495
 opp, before for target=5
 opp, after for target=5
 Result: 5

 $ ./theaded_program
 main, before for target=5
 opp, before for target=5
 opp, after for target=5
 main, after for target=-495
 Result: 5
4

2 に答える 2