User Tools

Site Tools


for_developers:thread_safety

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
for_developers:thread_safety [2019/09/10 11:47] – created kunzfor_developers:thread_safety [2019/11/01 10:11] (current) – Add link to source code kunz
Line 5: Line 5:
 Concurrency can not be tested by Google Test framework. Therefore, test executables are needed which can be executed manually or via bash scripts. Concurrency can not be tested by Google Test framework. Therefore, test executables are needed which can be executed manually or via bash scripts.
  
-To provide an example, a test program testing the Gain block is described in the following. The full source code is available at GitHub at: +To provide an example, a test program testing the Gain block is described below. The full source code is available on GitHub at: https://github.com/eeros-project/eeros-framework/blob/master/examples/development/multithreading.cpp 
 + 
 +===== The problem ===== 
 + 
 +The following code snipped and image show the issue simulated in the test program. The main thread calls **g1.run()** on the gain object. This method is doing a long calculation. Thread t2 is unfortunately changing the gain by calling **g1.setGain(gM2)** during the main threads calculation. This will finally lead to an unexpected result.   
 + 
 + 
 +<code> 
 +Matrix<M,N> gM1; 
 +Matrix<M,N> gM2; 
 + 
 +Gain<Matrix<M,N>, Matrix<M,N>,true> g1{gM1}; 
 +Constant<Matrix<M,N>> c1{m2}; 
 + 
 +std::thread t2{[&] { 
 +  g1.setGain(gM2); 
 +}}; 
 + 
 +g1.run(); 
 + 
 +Matrix<M,N> res = g1.getOut().getSignal().getValue(); 
 + 
 +// Note: The above code is simplified for a better understanding.  
 +</code> 
 + 
 + 
 +{{:for_developers:concurrencyissue.jpg?800|}} 
 + 
 + 
 +===== The solution ===== 
 + 
 +The Gain block is now implemented thread safe by using the class [[https://en.cppreference.com/w/cpp/thread/lock_guard|lock_guard]] and a [[https://en.cppreference.com/w/cpp/thread/mutex|mutex]]. The code snipped below shows the **setGain()** method as an example. 
 +  
 +<code> 
 +virtual void setGain(Tgain c) { 
 +  std::lock_guard<std::mutex> lock(mtx); 
 +  gain = c; 
 +
 +</code> 
 + 
 +The test program will not show an unexpected result anymore. To see the unexpected result, the locking mechanism must be removed (//comment std::lock_guard<std::mutex> lock(mtx);//). 
  
for_developers/thread_safety.1568108827.txt.gz · Last modified: 2019/09/10 11:47 by kunz