Home > Mobile >  Variables outside thread is updated one step behind
Variables outside thread is updated one step behind

Time:12-08

I have a simple program where I update an integer whenever I get a result from PLC. I create a thread and run a process inside the thread which checks for the result. There is a timer which calls the simulate process every 1 second(not shown here).

Problem is, the first time it triggers, the result is always 0, even if the process returns 1. From there on, the result is always one step behind. The value of variable "ok" will be 1 in the process, but in simulate method it will be 0.

Here is an example code :

                   int ok;
                    public void Simulate()
                    {
                        Thread simThread = new Thread(process);
                        simThread.Start()
                        
                        if(ok == 1)
                        {
                          lblResult.Text = "Ok";
                        }
                        
                        else 
                        {
                          lblResult.Text = " Not Ok";
                        }
                    }
                    
                    public void process()
                    {
                       GetValFromPLC();
                       if(PLCval == 1)
                         {
                           ok =1;
                         }
                       else 
                         {
                           ok = 0;
                         }
                       
                    }

If I run it without using thread, it works fine and I get the proper result. Why is the program behaving this way?

CodePudding user response:

Well, here you have what is called "race condition" in which Simulate is executed on the initial thread and although it launches the second thread for process(), the main thread executes the rest of its body till the OS schedule the execution slice to the second thread to run its code(probably most of the time...). Please see Symptoms for a race condition

So in order to synchronize the both threads you need to use sync objects, either crit sections, mutexes or events: Synchronization Good luck!

  • Related