[英]How to make thread safe program?
在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_lock(&my_mutex);
//使線程安全的代碼
調用pthread_mutex_unlock(&my_mutex);
將my_mutex聲明為像pthread_mutex_t my_mutex;
這樣的全局變量pthread_mutex_t my_mutex;
。 或者使用pthread_mutex_t my_mutex;
在代碼中初始化pthread_mutex_t my_mutex;
pthread_mutex_init(&my_mutex, NULL);
。 同樣不要忘記在編譯時包含#include <pthread.h>
並將程序與-lpthread
鏈接。
問題(在代碼中的注釋中):
//互斥鎖? futex的? 鎖? 信號? 其他?
答:互斥。
請參見pthread_mutex_init
, pthread_mutex_lock
和pthread_mutex_unlock
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.