多线程场景下fprintf输出格式异常问题求助
多线程环境下fprintf输出科学计数法格式随机异常问题
我编写了一个计算估计值并将其写入文件的函数,程序在多线程环境中被调用,针对不同初始条件执行计算。每个线程创建独立文件进行写入,不存在文件冲突,输出采用科学计数法。目前遇到的问题是:大部分数值输出正常,但有个别(1-2个)出现格式错误,比如指数部分缺失'e'、符号异常等,这导致后续依赖这些文件的程序解析失败。
线程创建循环代码
for (int i = 0; i < 12; i++) { void* args[2] = {clock_pairs[i], Q_matrices[i]}; pthread_create(&K_threads[i], NULL, calculate_kalman, (void*)args); printf("thread no %d ran \n",i); } for (int i = 0; i < 12; i++) { pthread_join(K_threads[i], NULL); }
核心计算函数代码
void Calculate_Kalman(const char *filename, const char *filename1, double** processNoise) { char kalman_filename[256]; sprintf(kalman_filename, "K_%s_%s", filename, filename1); FILE *kalman_file = fopen(kalman_filename, "w"); if (!kalman_file) { perror("Error opening file for writing"); exit(EXIT_FAILURE); } char Error_filename[256]; sprintf(Error_filename, "E_%s_%s", filename, filename1); FILE *E_file = fopen(Error_filename, "w"); if (!E_file) { perror("Error opening file for writing"); exit(EXIT_FAILURE); } for (int i = 0; i < SampleSize; i++) { kf.z = diff[i] + normalRandom(0,pow(measurementNoise,0.5)); Kalman(&kf); // Kalman function call. // Print the current state estimate fprintf(kalman_file, "%e, %e\n", gsl_matrix_get(kf.x, 0, 0), gsl_matrix_get(kf.x, 1, 0)); fprintf(E_file, "%e,%e\n", gsl_matrix_get(kf.S, 0, 0), gsl_matrix_get(kf.S, 1, 0)); // Add kf.S values to the dynamic matrix double row[NUM_VARS] = {gsl_matrix_get(kf.S, 0, 0), gsl_matrix_get(kf.S, 1, 0)}; addRow(&matrix, row); } fclose(kalman_file); }
KalmanFilter结构体定义
typedef struct { gsl_matrix *x; // State estimate (3x1 matrix) gsl_matrix *P; // Error covariance (3x3 matrix) gsl_matrix *Q; // Process noise covariance (3x3 matrix) double R; // Measurement noise covariance (scalar) gsl_matrix *K; // Kalman gain (3x1 matrix) gsl_matrix *Phi; // State transition matrix (3x3 matrix) gsl_matrix *S; // Noise vector (3x1 matrix) gsl_matrix *H; double z; } KalmanFilter;
输出示例
正常输出
-3.257449e-15, -1.437916e-18 8.742356e-11, 5.662028e-14 -1.929949e-10, -1.779626e-13 1.927338e-10, 2.305067e-13 -8.744399e-11, -1.284666e-13 ........................ ........................
异常输出
-3.0.049398e-13
1.-12
- -1.922051e-13
已尝试的解决方法
- 更换格式化样式,使用
%le替代%e,问题依旧存在。
异常出现的位置和文件完全随机,无法定位具体原因,希望得到解决思路或方案。
内容的提问来源于stack exchange,提问作者Sougandh Km
相关产品推荐
相关产品推荐

