如何制作线程安全程序?

时间:2016-03-11 00:01:10

标签: c multithreading

在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

2 个答案:

答案 0 :(得分:3)

  

的pthread_mutex_lock(安培; my_mutex);

     

//使线程安全的代码

     

调用pthread_mutex_unlock(安培; my_mutex);

将my_mutex声明为全局变量,如pthread_mutex_t my_mutex;。或者使用pthread_mutex_t my_mutex; pthread_mutex_init(&my_mutex, NULL);在代码中初始化。另外,请不要忘记在编译时添加#include <pthread.h>并将您的程序与-lpthread相关联。

答案 1 :(得分:1)

问题(在代码中的评论中):

  

//互斥? futex的?锁?信号?其他

答案:互斥。

请参阅pthread_mutex_initpthread_mutex_lockpthread_mutex_unlock