我有一堂课,下面有2个函数;
// Function to calculate the sum and average temperature
float read_samples(float *data, int num_samples)
{
float sum = 0.0;
float average = 0.0;
for(int i = 1; i < num_samples; i++ ) {
data[i] = temperature.read();
sum = sum + data[i];
wait(1);
}
average = sum / (num_samples - 1);
return average;
}
// Main Function that is called on running the application
int main()
{
int num_samples = 12 / 1;
float data[num_samples];
//sw.fall(read_samples(data, num_samples));
while(1) {
wait(12);
float result = read_samples(data, num_samples);
lcd.printf("%.2f\n", result);
//data[0];
}
}
当我调用“ wait(12);”时在Main方法中,我希望代码在等待的同时执行“ read_samples”方法,当“ read_samples”完成后,返回计算出的值,然后继续在Main函数中显示计算出的结果。计算应该在等待的12秒内进行。
但是,现在正在发生的事情是,在等待的12秒钟内没有执行任何操作,因此在等待12秒钟后,它将调用“ read_samples”方法,并再执行11秒钟。因此,显示下一个结果所花费的总时间为(12 + 11)23秒。请问,如何在等待12秒的时间内编写代码以执行“ read_samples”方法?
答案 0 :(得分:0)
您可以在单独的线程中运行read_samples
。例如:
static float average = 0.0f;
// Function to calculate the sum and average temperature
void read_samples()
{
int num_samples = 12 / 1;
float data[num_samples];
float sum = 0.0;
for(int i = 1; i < num_samples; i++ ) {
data[i] = temperature.read();
sum = sum + data[i];
wait(1);
}
average = sum / (num_samples - 1);
}
// Main Function that is called on running the application
int main()
{
//sw.fall(read_samples(data, num_samples));
while(1) {
Thread sampleThread;
sampleThread.start(&read_samples);
wait(12);
lcd.printf("%.2f\n", result);
//data[0];
}
}
您需要保护通过Mutex对average
的访问。