LabWindows/CVI

cancel
Showing results for 
Search instead for 
Did you mean: 

problem with kill threads labwindows

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.

0 Kudos
Message 1 of 4
(4,581 Views)

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

Message Edited by OVR_CZ on 11-30-2009 10:07 AM
0 Kudos
Message 2 of 4
(4,528 Views)
Thanks you very much for your answer. The program I have to do is this: I have to communicate with some instruments to get some data. Some of readings take some time to execute.The user interface is quite big. For that I need to have the measurements reading in threads (not in normal timersbecause of the use of the CPU). I have done the same thing in some different ways. The first time I have create 3 threads, and during all the test arerunning and with a flag, controllated by a normal timer, I control the period time between measurements. Until the end of the test I don`t destroy any thread and only put the instruction SetSleepPolicy to have some CPU timefor other processes. With this way the use of the CPU is always high, and when the program is running during nearly1000 minutes the system falls down and you have to close the application by force. Other thing I wanted to do and I have tried is to stop the thread each time the code of the thread has been finish executing. Thus during the time the thread has finished executing its code until the time the timer tells the thread to start again, the thread is stopped and there are more CPU time for the other process. This way is very good for the consumption of the processor but as same as before the program fall down during 1000 minutes. I thing is better to create only 3 threads and then know when they are sleeping and when they have to be awake. But I am not really sure how to do this. Can I stop a thread (sleep) inside the own thread? And what are the instructions to wake up inside a normal timer? There is any example of this? I have been reading some documentation but I don’t find what I need. Also I have tried to use the asynchronous timer you tell me. In a little program works fine but in a big one not all the code inside the timers executes. I don’t know how this timer works. Do you have any idea why after some time (1000 minutes) the program falls down? Thank you very much for your time. Also Sorry for my English
0 Kudos
Message 3 of 4
(4,503 Views)

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 😉

0 Kudos
Message 4 of 4
(4,490 Views)