首页 > 解决方案 > 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);
}

标签: pthreadsbufferdata-acquisition

解决方案


您没有初始化data.n_intdata.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.005usecs只会将其设置为零。


推荐阅读