pthreads - C p_thread:分段错误
问题描述
我正在尝试实现一个循环缓冲区以从加速度计获取数据并将信息导出到 csv。加速度计的读数必须具有恒定的周期。我使用 p_thread 同时运行读取和导出功能,但它给了我一个分段错误错误。另外,我不确定使用 p_thread 是否可以导出多个值。你能帮我解决我的问题吗?
#include <stdio.h>
#include "MPU-9150.h"
#include <stdint.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#define nBuff 32
struct thread_data{
double ax_buff[nBuff];
double ay_buff[nBuff];
double gz_buff[nBuff];
int n_int;
int n_save;
};
void *reader( void *threadarg) {
int ret;
struct thread_data *my_data;
my_data = (struct thread_data *) threadarg;
time_t usecs = 0.005; // 0.005 seconds
while(1) {
time_t ustartTime = time(NULL);
while (time(NULL) - ustartTime == usecs) {
if (my_data->n_int + 1 != my_data->n_save) {
ret = imupi_read( my_data->ax_buff[my_data->n_int], my_data->ay_buff[my_data->n_int], my_data->gz_buff[my_data->n_int] );
if ( ret ) {
mpu_read_error(ret);
}
my_data->n_int = (my_data->n_int+1) % nBuff;
}
}
}
}
void main( void ) {
int ret;
// Set acquisition timer
struct thread_data data;
pthread_t my_thread;
// Initialization of the MPU-9150
if ( ret = imupi_init( ) ) {
mpu_init_error(ret);
}
//Open Data File
/*FILE *fid = fopen("mpu_cal.csv", "w");
if (fid == NULL) {
perror("Error opening file\n");
exit(1);
}*/
if (pthread_create(&my_thread, NULL, reader, (void *) &data)) {
fprintf(stderr, "Error creating thread\n");
exit(1);
}
// Set full timer
time_t secs = 30; // 30 seconds
time_t startTime = time(NULL);
while (time(NULL) - startTime < secs) {
if (data.n_save != data.n_int) {
printf( "%f,%f,%f\n", data.ax_buff[data.n_save], data.ay_buff[data.n_save], data.gz_buff[data.n_save]);
//fflush(stdout);
data.n_save = (data.n_save+1) % nBuff;
}
}
//fclose(fid);
exit(1);
}
解决方案
您没有初始化data.n_int
和data.n_save
. 最简单的解决方法是在声明中添加一个初始化程序:
struct thread_data data = { .n_int = 0, .n_save = 0 };
此外,您将double
值传递给imupi_read()
它出现时应该采用指针:
ret = imupi_read(&my_data->ax_buff[my_data->n_int],
&my_data->ay_buff[my_data->n_int], &my_data->gz_buff[my_data->n_int]);
您将面临的另一个问题是,在常见平台上time_t
是整数类型,因此分配0.005
给usecs
只会将其设置为零。
推荐阅读
- c++ - 像 VS Code 一样在 c++ popen() 中启动应用程序
- java - 折叠数组
- reactjs - 在 Jest 中存根 I18next useTranslation 钩子不会触发 toHaveBeenCalled
- python - 使用 Python 将文件从本地计算机传输到 Sharepoint 文件夹
- javascript - Discord.js 记住用户输入以供以后使用(又名 args)
- xcode - Bundle-Id 中的前缀错误,应为 Team Id
- python - 禁止直接分配到相关集的反面
- c++ - 在 cpp 中生成 128 位泊松分布数
- makefile - 依赖列表中 OR 运算符的用途是什么?
- google-tag-manager - Google 跟踪代码管理器:将“所有自定义事件”与事件条件一起使用