在64位体系结构pc上,下一个程序应返回结果1.350948。
但它不是线程安全的,而且每次运行它都会给出(显然)不同的结果。

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

const unsigned int ndiv = 1000;
double res = 0;

struct xval{
  double x;
};

// Integrate exp(x^2 + y^2) over the unit circle on the
// first quadrant.
void* sum_function(void*);
void* sum_function(void* args){
  unsigned int j;
  double y = 0;
  double localres = 0;
  double x = ((struct xval*)args)->x;

  for(j = 0; (x*x)+(y*y) < 1; y = (++j)*(1/(double)ndiv)){
    localres += exp((x*x)+(y*y));
  }

  // Globla variable:
  res += (localres/(double)(ndiv*ndiv));
  // This is not thread safe!
  // mutex? futex? lock? semaphore? other?
}

int main(void){
  unsigned int i;
  double x = 0;

  pthread_t thr[ndiv];
  struct xval* xvarray;

  if((xvarray = calloc(ndiv, sizeof(struct xval))) == NULL){
    exit(EXIT_FAILURE);
  }

  for(i = 0; x < 1; x = (++i)*(1/(double)ndiv)){
    xvarray[i].x = x;
    pthread_create(&thr[i], NULL, &sum_function, &xvarray[i]);
    // Should check return value.
  }

  for(i = 0; i < ndiv; i++){
    pthread_join(thr[i], NULL);
    // If
    // pthread_join(thr[i], &retval);
    // res += *((double*)retval) <-?
    // there would be no problem.
  }

  printf("The integral of exp(x^2 + y^2) over the unit circle on\n\
    the first quadrant is: %f\n", res);

  return 0;
}

怎么可能是线程安全的?
注意:我知道1000个线程不是解决这个问题的好方法,但是我真的很想知道如何编写线程安全的c程序。

gcc ./integral0.c -lpthread -lm -o integral

最佳答案

问题(在代码的注释中):
//互斥?未来?洛克?信号量?其他的?
答:互斥。
请参见pthread_mutex_initpthread_mutex_lockpthread_mutex_unlock

关于c - 如何制作线程安全程序?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35929749/

10-11 19:39
查看更多