11-27-2009 07:56 AM
I want tocreate an kill a thread each five seconds.
With atimer I create a thread.
In thefunction of this thread I execute some functions (they take 3second to finishall functions) and when it has been finished,
I want to kill the thread.
Then, whenthe timer interrupts again, I want to create the same thread to do the sameprocess as I have just described.
Can I dothis? How can I do this?
I have donein a way I don't sure it is working fine because of the memory or the resourcesused.
In thetimer I do this:
WaitAcquisitionIrrad=1;
//CREACIÓN DEL HILO DE MEDIDA DE LA IRRADIANCIA
threadFlagMeasureIrrad=0;
CmtScheduleThreadPoolFunction(DEFAULT_THREAD_POOL_HANDLE, ThreadMeasureIrradiance,NULL,&threadFunctionId2);
In thetrhead callack function i do this
intCVICALLBACK ThreadMeasureIrradiance(void *fucntionData)
{
int RetVal;
char cadena[256];
while(!threadFlagMeasureIrrad)
{
if(WaitAcquisitionIrrad==1)
{
//LECTURADEL PLC DE LA FUENTE DEULTRAVIOLETA
RetVal=Read_data_from_UV_lamp();
RetVal=PlotStripIrrad();
RetVal=Display_UIR(IRRADIANCE);
//GUARDARLOS DATOS DE IRRADIANCIA EN UN FICHERO
RetVal=Save_plc_info(irradiancia.real_values,irradiancia.int16_values,
irradiancia.state_lamps_bool,irradiancia.state_shutter,
irradiancia.lamps_on_off,irradiancia.error_memory);
WaitAcquisitionIrrad=0;//para que tenga que volver a interrumpir el timer PARA volver a medir
threadFlagMeasureIrrad=1;//matar_a_hilo_de_irradiancia
}
}
SetSleepPolicy(VAL_SLEEP_SOME);//para que el hilo deje libre al procesador un tiempo pequeño
return 0;
}
The CPU consumptionsis growing up during the application is working, ant some time later theprogram collapse the Operate System.
What I am doingwrong.
Thank youfor your help.
11-30-2009 03:03 AM - edited 11-30-2009 03:07 AM
Hi,
i`m not sure if understnd correctly what you need, but there is few general tips(for detail see to CVI help:) )
first of all, if you not familiar with multithread,search internet for information about multithreading programing , thread synchronisation, etc... or read some book about it, sometims it is very hard to find/debug problems with this type of application, without the right knowledge.
a)maybe NewAsyncTimer(toolslib\toolbox\asynctmr.fp) is more simple and adequate than directly use threads functions(if you only need action in other threads with specific time cykle)
b)better than create and kill thread frequently, is create thread once, and control him (start measure, stop measure,exit thread)
with some thread safe function(see to CmtNewTSQ,CmtNewTSV,CmtNewLock)
c)if use variable between threads, it is need to encapsulate by somethink like CmtNewTSV(there is exeption for some atomic variable type-int, but is nesscesary to define variable with volatile prefix
like volatile int WaitAcquisitionIrrad;but i recomended to use Cmt* functions instead)
d)on one processor(core) mashine, only one thread can run in time, if you consume all CPU power with somthing like
while (flagWaiting==1);other process and threads works realy slow{depends on priority,OS version,..}
so use some waiting function{Sleep();CmtReadTSQData;...} if you wait in thread
(it is also best to save CPU power, regardles of number of CPU core)
e)assume that thread is done after 3(or any other time)second is not good practice, use som flag(threadsafe) to be sure or CmtWaitForThreadPoolFunctionCompletion for waiting to finish the thread.(this is also for assuming that thread is started)
e)in other than main thread, do not work directly with UI, use ThreadSafeQueue or something similar.
it`s seems to be unnecessary with CVI UI functions which is multithread safe, but i do not recomend this.
if you realy need to this, then be sure to work only with panel that is loaded/created in the same thread,
but there is problem with this panel because it`s screen order is independent between panel from other/main threads
(for example, MessagePopup, or InstallPopup can be silently hidden below themain panel, so user is not forced to
react to message/panel)
f)using library (for example to communicate with instrument) in multiple thread is somtimes like nightmare
first try find if there is some doc about multithreading use of your library.
(but be prepared to diferences:for example:CVI serial library is perfectly safe, but some specific drivers for USB-serial do not work well if you call it from multiple threads,but when i open and use in one thread then works OK)
g) for long time running application(24h-7days in week), is nesscesary to be sure what you doing, and also need long time testing, beacause some "races" can arise sporadically(my record is race after one month of application run)
at the end:"windows is not real time operating system", so timing below 100ms is maybe possible, but not easy or guarantied 🙂
i hope this help
P.S. //sory for my english
12-01-2009 02:38 AM
12-01-2009 08:25 AM
hi,
SetSleepPolicy do not set thread to sleep, only configure how long sleep is
for Sleep use ProcessSystemEvents();{fom utility.h}, or better Sleep(DWORD dwMilliseconds){Windows.h}
there are two base approach to synchronize works from main to work thread:
!next examples is only concept, it is needed to add error checking, thread safe acces to shared variables, !
!and Thread safe acess to shared data(readed from device).!
!Also there is no check from main thread if request to read data(or to exit thread) is processed or not!
1)check periodicaly(with sleep) if new request is comming from main threat, with some Sleep time after everey check
void ThreadFunc()
{
while (FlagThreadExitFlag==0)//proceed ony when flag for close thread is not set { //wait to new request while((flagNeedReadNewData==0)||(FlagThreadExitFlag==0))Sleep(10); if (FlagThreadExitFlag!=0)return;//exit thread if flag is set
Read Data();
}
}
//to run ReadData
flagNeedReadNewData=1;
//to request thread exit
FlagThreadExitFlag=1;
2)after all work in thread is done, use some wait function to synchronize with main thread
(ThreadSafeQueue in example)
somewhere in initialization int hTSQ; Init() { CmtNewTSQ (10, sizeof(int), OPT_TSQ_DYNAMIC_SIZE,&hTSQ);//setup to ThreadSafeQueue of int variables
} void ThreadFunc() {int Command,r; while (FlagThreadExitFlag==0)//proceed ony when flag for close thread is not set { r=CmtReadTSQData(ThrData->TSQ,&Command,1,MaxWaitTime,0); if (r==1)//comand read from queue { if (Command==1)Read data(); if (Command==-1)Return;//exit thread } if (r<0)return;//error } return; } int SendCommand; //to run Read data you can send: SendCommand=1; CmtWriteTSQData(ThrData->TSQ,&SendCommand,1,0,0)!=1)return -1; //to send request to close thread SendCommand=-1; CmtWriteTSQData(ThrData->TSQ,&SendCommand,1,0,0)!=1)return -1;
(you can also use second queue to delivery data back to main thread)
there is also som other wait function in Winapi like Mutex(CreateMutex),Semaphore(CreateSemaphore),Event(CreateEvent)
you can find lot of information on MSDN web about this func.
alsou you can also search for phrase multithread synchronization on google
i have no idea why your program fails after long time
(time interval 1000m is too long or short compared to any problems that i chalenge before)
there can be lot of things that can be wrong, from unitialized pointer/variable, forgoten discard resource(memory leaks) to bug in device library or some problem with multithreading acess to shared variable or thread synchronization.
but there is two general tips that can help you with debuging multithread aplication
temporary move code from extra thread to main thread{to check and debug comunication routine}
and/or
try substitute Read Data code by some Simulation code (just set value to right or random val){to chcek fo multithread problems)
good luck to huntig the bug 😉