[英]DiscardAsyncTimer returning before timer callback is complete
我正在嘗試使用異步計時器在LabWindows / CVI 2017中編寫程序,但是遇到了DiscardAsyncTimer()函數的問題。 從DiscardAsyncTimer()的文檔中:
在所有未完成的異步回調返回之前,創建或放棄異步計時器的調用將不會完成(將阻塞)。
但是,在調用DiscardAsyncTimer()之后,我在釋放異步計時器線程中使用的內存時遇到了一些內存問題。 我希望不再使用該內存,但是顯然不是這樣嗎? 我下面有一個示例程序,該程序重新創建了我的問題。 運行時,此程序由於嘗試訪問釋放的內存而生成“一般保護錯誤”。 但是,如果我對文檔以及文檔本身的理解是正確的,那應該是不可能的,因為應該在所有回調返回之前阻塞DiscardAsyncTimer()。
我的問題:
示例程序:
#include <ansi_c.h>
#include <asynctmr.h>
#include <stdio.h>
#include <utility.h>
#include <userint.h>
typedef struct {
int* array;
} MyStruct;
int CVICALLBACK ShuffleValues (int reserved, int timerId, int event, void *callbackData, int eventData1, int eventData2)
{
if (event == EVENT_TIMER_TICK) {
printf("start\n");
MyStruct* mystruct = callbackData;
// Shuffle values
for(int i = 0;i < 1000;i++) {
mystruct->array[0] = mystruct->array[1];
mystruct->array[1] = mystruct->array[2];
Delay(0.01);
}
printf("finished\n");
}
return 0;
}
int main ()
{
// Allocate memory
MyStruct* mystruct = malloc(sizeof(MyStruct));
mystruct->array = malloc(10 * sizeof(int));
// Start Async Timer
int timer = NewAsyncTimer(0.01, -1, 1, ShuffleValues, mystruct);
// Wait a while to let the timer thread run a bit
Delay(0.5);
// Destroy Async Timer
printf("start destroying\n");
int retval = DiscardAsyncTimer(timer);
printf("finished destroying: %d\n", retval);
// Free memory now that the timer thread is no longer running
free(mystruct->array);
free(mystruct);
Delay(1);
return 0;
}
我還於一周前在LabWindows / CVI論壇上問了這個問題,沒有任何回應: https : //forums.ni.com/t5/LabWindows-CVI/DiscardAsyncTimer-returning-before-timer-callback-is-complete/td- p / 3943460
我在NI論壇上沒有看到您的問題。 快速的答案是異步計時器在單獨的線程中運行,因此您需要采取通常的預防措施。 發生錯誤時,您可以使用[Windows] [Threads]看到該錯誤,並從一個線程跳轉到另一個線程。 使用易失性變量進行同步,或者更好地使用信號量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.