kandi background
Explore Kits

MTX | Compact Mtx Framework over LibGDX Game Library | Game Engine library

 by   moribitotech Java Version: Current License: No License

 by   moribitotech Java Version: Current License: No License

Download this library from

kandi X-RAY | MTX Summary

MTX is a Java library typically used in Gaming, Game Engine applications. MTX has no bugs, it has no vulnerabilities, it has build file available and it has low support. You can download it from GitHub.
How can it be used:.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • MTX has a low active ecosystem.
  • It has 61 star(s) with 29 fork(s). There are 18 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 1 open issues and 1 have been closed. On average issues are closed in 3 days. There are 1 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of MTX is current.
MTX Support
Best in #Game Engine
Average in #Game Engine
MTX Support
Best in #Game Engine
Average in #Game Engine

quality kandi Quality

  • MTX has 0 bugs and 0 code smells.
MTX Quality
Best in #Game Engine
Average in #Game Engine
MTX Quality
Best in #Game Engine
Average in #Game Engine

securitySecurity

  • MTX has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • MTX code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
MTX Security
Best in #Game Engine
Average in #Game Engine
MTX Security
Best in #Game Engine
Average in #Game Engine

license License

  • MTX does not have a standard license declared.
  • Check the repository for any license declaration and review the terms closely.
  • Without a license, all rights are reserved, and you cannot use the library in your applications.
MTX License
Best in #Game Engine
Average in #Game Engine
MTX License
Best in #Game Engine
Average in #Game Engine

buildReuse

  • MTX releases are not available. You will need to build from source code and install.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • MTX saves you 3373 person hours of effort in developing the same functionality from scratch.
  • It has 7234 lines of code, 734 functions and 120 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
MTX Reuse
Best in #Game Engine
Average in #Game Engine
MTX Reuse
Best in #Game Engine
Average in #Game Engine
Top functions reviewed by kandi - BETA

kandi has reviewed MTX and discovered the below as its top functions. This is intended to give you an instant insight into MTX implemented functionality, and help decide if they suit your requirements.

  • Sets up the btnSocial buttons .
    • Set up up touch listener for the input intent .
      • Set the position of an actor
        • Set up the scene .
          • Sets the new screen with transitions .
            • Set the animation to be executed .
              • Initialize the main world .
                • Set the current snowflake region .
                  • Set the origin of an actor .
                    • Set up the seeds .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      MTX Key Features

                      Compact-MTX framework over LibGDX Scene2D

                      Tutorial Blog: http://moribitotechx.blogspot.co.uk/

                      Twitter: https://twitter.com/MoribitoTech

                      Exclusive Facebook Group: https://www.facebook.com/groups/MoribitoTechAndroid/

                      Basic knowledge and experience with Java, Android SDK, Eclipse and LibGDX

                      Understanding the fundamentals of LibGDX Scene2D

                      TexturePacking and TextureAtlas management (Not essential)

                      MTX Examples and Code Snippets

                      See all related Code Snippets

                      default

                      copy iconCopydownload iconDownload
                      - It is a Open Source Project Under Apache Licence, Version 2.0
                      - %100 Free and Awsome
                      - Designed for Apps, Games & Live Wallpapers (Extremely easy and fast)
                      - Designed for far less code writing
                      - Built over LibGDX Scene2D
                      - Cross device resolution (Same quality in every device wiht Mtx v2.0 version, no more stretching)
                      - Designed for easier Scene / Stage / Group / Actor integration
                      - Designed for easier Menu Creations
                      - Designed for easier Animation Integration
                      - Designed for easier Settings Management
                      - Ready effects and smart models
                      - Designed for game specific purposes. For example, creating level buttons, setting special animations, getting screen time, integrating momentarily animations, multi-textured buttons, advanced actors, special setting management (volume, vibration, sfx and others.).
                      - Also usable for game logics, but it is heavily depends on Scene2D, it means that it is not %100 MVC supportive. However for games like puzzles, brain teasers, low-level platformers, low-level defence games, other low-level causal games, it may be suitable. Again, I warn you, it is not %100 MVC supportive.
                      
                      What you need to know:

                      Accept and return lambda (lock wrapper)

                      copy iconCopydownload iconDownload
                      template<typename Func>
                      auto DoLocked(Func func) -> decltype(func(*this)) {
                          std::lock_guard<std::mutex> lock(*mtx);
                          return func(*this);
                      }
                      

                      Why does Condvar thread never wake up?

                      copy iconCopydownload iconDownload
                      use std::{
                          sync::{
                              atomic::{AtomicBool, Ordering},
                              Barrier,
                          },
                          thread,
                      };
                      
                      fn do_work(
                          start_barrier: &Barrier,
                          finish_barrier: &Barrier,
                          quitting: &AtomicBool,
                          starting: &AtomicBool,
                          finishing: &AtomicBool,
                          range: &mut [f32],
                      ) {
                          while !quitting.load(Ordering::SeqCst) {
                              start_barrier.wait();
                              while !starting.load(Ordering::SeqCst) && !quitting.load(Ordering::SeqCst) {}
                              {
                                  // let mut started = mtx.lock().unwrap();
                                  // while !*started && !quitting.load(Ordering::SeqCst) {
                                  //     started = cond_var.wait(started).unwrap();
                                  // }
                              }
                              if quitting.load(Ordering::SeqCst) {
                                  break;
                              } else {
                                  range.iter_mut().for_each(|i| *i += 1.0);
                              }
                              finish_barrier.wait();
                              while !finishing.load(Ordering::SeqCst) && !quitting.load(Ordering::SeqCst) {}
                          }
                          println!("{:?} Joining", thread::current().id());
                      }
                      
                      fn main() {
                          let num_threads = 4;
                          let start_barrier = Barrier::new(num_threads + 1);
                          let finish_barrier = Barrier::new(num_threads + 1);
                          let mut my_data = vec![0.0; 1024];
                          my_data
                              .iter_mut()
                              .enumerate()
                              .for_each(|(i, iter)| *iter = i as f32);
                          let chunk_size = my_data.len() / num_threads;
                          let quitting = AtomicBool::new(false);
                          let starting = AtomicBool::new(false);
                          let finishing = AtomicBool::new(false);
                      
                      
                          rayon::scope(|s| {
                              for chunk in my_data.chunks_mut(chunk_size) {
                                  let thread_start_barrier = &start_barrier;
                                  let thread_finish_barrier = &finish_barrier;
                      
                                  let thread_quitting = &quitting;
                                  let thread_starting = &starting;
                                  let thread_finishing = &finishing;
                      
                                  s.spawn(move |_| do_work(   thread_start_barrier,
                                                              thread_finish_barrier,
                                                              thread_quitting, 
                                                              thread_starting,
                                                              thread_finishing,
                                                              chunk));
                              }
                              let num_rounds = 10;
                              for i in 0..num_rounds {
                                  let start = std::time::Instant::now();
                                  start_barrier.wait();
                                  finishing.store(false, Ordering::SeqCst);
                                  starting.store(true, Ordering::SeqCst);
                                  finish_barrier.wait();
                                  if i == num_rounds-1 {
                                      quitting.store(true, Ordering::SeqCst);
                                  }
                                  finishing.store(true, Ordering::SeqCst);
                                  starting.store(false, Ordering::SeqCst);
                                  println!("Round {} took: {:?}", i, std::time::Instant::now() - start);
                              }
                          });
                          println!("my_data is: {:?}", my_data);
                      }
                      

                      Audio matlab challenge: Reverberation, FDN, Filtering

                      copy iconCopydownload iconDownload
                      % Feedback Delay Network - Mono
                      % Creates impulse response based on reverberation times
                      
                      fs = 44100;
                      in = [ 1; 0 ];            % Dirac Impulse
                      in = [in; zeros(3*fs,1)]; % Space for reverb
                       
                      % Householder matrix N=16
                      A = eye(4) - ( 2/4 * ones(4,1) * ones(1,4) );
                      MTX = .5 * [A -A -A -A; -A A -A -A; -A -A A -A; -A -A -A A];
                      
                      N = size(MTX,1);    % Matrix order
                      
                      delays = randi([dmin dmax],N); % N delays
                      
                      load('GEQ.mat');    % Third octave graphic equalizer calculated based
                                          % on an atenuation-per-sample and scaled by delays.
                                          % SOS Form Size 31x6xN 
                                         
                      % Initialize signals
                      delayBuffer = max(delays) + max(delays)/10;
                      bufferN = zeros(delayBuffer,N);   % Delay buffers
                         buffFin = zeros(31,3,N);         % New buffers for filter outputs
                         buffFout = zeros(31,3,N);
                      FB = zeros(1,N);               % Feedback matrix output
                      in_dl = zeros(1,N);            % Delay input
                      out_dl = zeros(1,N);           % Delay output
                         out_fdl = zeros(1,N);            % Filtered delay output
                      nSample = length(in);          % Number of samples
                      out = zeros(nSample,1);        % Output
                       
                      % FDN Computation
                      for sample = 1:nSample     % each sample
                          for n = 1:N            % each delayline
                               
                             in_dl(n) = in(sample,1) + FB(n); % Input and Feedback matrix sum
                             
                             % Delaying
                             [out_dl(n),bufferN(:,n)] = funcDelay( in_dl(n), bufferN(:,n),...
                                                 sample, delays(n) );
                             % Filtering
                             [out_fdl(n),buffFin(:,:,n),buffFout(:,:,n)] = funcFilterGEQ(...
                                  GEQ(:,:,n), out_dl(n), buffFin(:,:,n), buffFout(:,:,n));  
                          end
                           
                          out(sample,1) = sum(out_fdl); % Filtered delay output sum
                           
                          FB = out_fdl * MTX; % Feedback matrix output recalculation
                      end
                      
                      
                      % Used functions
                      function [out,buffer] = funcDelay( in, buffer, n, delay)
                        
                        % Circular buffer indices
                        len = length(buffer);
                        indexC = mod(n-1, len) + 1;        % Current
                        indexD = mod(n-delay-1, len) + 1;  % Delay
                        
                        out = buffer(indexD,1);
                        
                        % Stores output on appropriate index
                        buffer(indexC,1) = in; 
                      end
                      
                      function [outfilt,buffin,buffout] = funcFilterGEQ( GEQ, in, buffin, buffout)
                                                % Sample based filter cascading
                      nBands = size(GEQ,1);
                      
                      out = zeros(1,nBands+1);
                      out(1) = in;              % Stores value pre-filtered
                                                
                      for b = 1:nBands          % Performs series bandpass filtering
                          [out(b+1),buffin(b,:),buffout(b,:)] = funcBandpassFilt( out(b),...
                              GEQ(b,1:3), GEQ(b,5:6), buffin(b,:), buffout(b,:) );
                      end
                      
                      outfilt = out(end);       % Outputs final value post-filtered
                      end
                      
                      function [out,buffin,buffout] = funcBandpassFilt( in, bs, as, buffin, buffout)
                                                % Sample based filtering
                      buffin(3) = buffin(2);    % Valid for biquad filters
                      buffin(2) = buffin(1);    
                      buffin(1) = in;           % Sequential indexing
                      
                      buffout(1) = bs(1)*buffin(1) + bs(2)*buffin(2) + bs(3)*buffin(3)...
                                                      - as(1)*buffout(2) - as(2)*buffout(3);
                      out = buffout(1);         
                                                % Outputs calculation based on 3 latest values
                      buffout(3) = buffout(2);
                      buffout(2) = buffout(1);  
                      buffout(1) = 0;
                      end
                      

                      How I can run two threads parallelly one by one?

                      copy iconCopydownload iconDownload
                      #include <mutex>
                      #include <iostream>
                      #include <vector>
                      #include <thread>
                      #include <condition_variable>
                      using namespace std;
                      
                      class CuncurrentThread
                      {
                      public:
                          mutex mtx;
                          condition_variable cv;
                          static bool ready;
                          //static bool processed;
                          void procThread1()
                          {
                              for (int i = 0; i < 100; i += 2)
                              {
                                  unique_lock<mutex> lk(mtx);
                                  // cv.notify_one();
                                  // if(lk.owns_lock())
                      
                                  // wait until this condition is true i.e. until ready is false
                                  cv.wait(lk, [&]() { return !ready; });
                                  cout << "procThread1 : " << i << "\n";
                      
                                  // set ready to true and notify waiting thread
                                  ready = true;
                                  lk.unlock();
                                  cv.notify_one();
                              }
                          };
                          void procThread2()
                          {
                              for (int i = 1; i < 100; i += 2)
                              {
                                  unique_lock<mutex> lk(mtx);
                                  // cv.notify_one();
                                  // if (lk.owns_lock())
                      
                                  // wait until this condition is true i.e. until ready is true
                                  cv.wait(lk, [&]() { return ready; });
                                  cout << "procThread2 : " << i << "\n";
                      
                                  // set ready to false and notify waiting thread
                                  ready = false;
                                  lk.unlock();
                                  cv.notify_one();
                              }
                          };
                          static void ThreadDriver(CuncurrentThread* thr)
                          {
                              vector<thread> threads;
                              threads.push_back(thread(&CuncurrentThread::procThread1, thr));
                              threads.push_back(thread(&CuncurrentThread::procThread2, thr));
                      
                              for (auto& thread : threads) 
                                  thread.join();
                      
                          };
                      };
                      bool CuncurrentThread::ready = false;
                      int main()
                      {
                          CuncurrentThread tr;
                          CuncurrentThread::ThreadDriver(&tr);
                      }
                      
                      #include <future>
                      #include <condition_variable>
                      #include <iostream>
                      
                      // Setup a helper class that sets up
                      // the three things needed to correctly
                      // use a condition variable
                      // 1) a mutex
                      // 2) a variable
                      // 3) a condition_variable (which is more of a signal then a variable)
                      //
                      // also give this class some functions
                      // so the the code becomes more self-explaining
                      
                      class thread_switcher_t
                      {
                      public:
                          void thread1_wait_for_turn()
                          {
                              std::unique_lock<std::mutex> lock{ m_mtx };
                              m_cv.wait(lock, [&] {return (thread_number==0); });
                          }
                      
                          void thread2_wait_for_turn()
                          {
                              std::unique_lock<std::mutex> lock{ m_mtx };
                              m_cv.wait(lock, [&] {return (thread_number==1); });
                          }
                      
                          void next_thread()
                          {
                              std::unique_lock<std::mutex> lock{ m_mtx };
                              thread_number = (thread_number + 1) % 2;
                              m_cv.notify_all();
                          }
                      
                      private:
                          std::size_t thread_number{ 0 };
                          std::mutex m_mtx;
                          std::condition_variable m_cv;
                      };
                      
                      
                      int main()
                      {
                          thread_switcher_t switcher;
                          
                          auto future1 = std::async(std::launch::async, [&]
                          {
                              for(std::size_t n = 0; n <= 100; n+=2)
                              {
                                  switcher.thread1_wait_for_turn();
                                  std::cout << "thread 1 : " << n << "\n";
                                  switcher.next_thread();
                              }
                          });
                      
                          auto future2 = std::async(std::launch::async, [&]
                          {
                              for (std::size_t n = 1; n <= 100; n += 2)
                              {
                                  switcher.thread2_wait_for_turn();
                                  std::cout << "thread 2 : " << n << "\n";
                                  switcher.next_thread();
                              }
                          });
                      
                          future1.get();
                          future2.get();
                      
                          return 0;
                      }
                      

                      How to use std::acumulate for matrix

                      copy iconCopydownload iconDownload
                      #include <iostream>
                      #include <numeric>
                      #include <vector>
                      
                      using Number = int;
                      using Matrix = std::vector<std::vector<Number>>;
                      
                      int main() {
                        Matrix mtx{5, std::vector<Number>(5, 1)};
                      
                        Number sum_positives = std::accumulate(
                            mtx.begin(), mtx.end(), Number(0), [](Number const acc, auto const &v) {
                              return std::accumulate(
                                  v.begin(), v.end(), acc,
                                  [](Number const a, Number const b) { return b > 0 ? a + b : a; });
                            });
                      
                        std::cout << sum_positives << std::endl;  // 25
                        return 0;
                      }
                      
                      int sum{0};
                      auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints
                      std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });
                      
                      auto sum{ std::ranges::accumulate(jv, 0, [](auto total, auto n) { return total + ((n > 0) ? n : 0); }) };
                      
                      #include <algorithm>  // for_each
                      #include <iostream>  // cout
                      #include <random>  // default_random_engine, uniform_int_distribution
                      #include <ranges>  // for_each, join_view
                      #include <vector>
                      
                      using matrix = std::vector<std::vector<int>>;
                      
                      int main()
                      {
                          matrix mtx{3, std::vector<int>(3)};
                      
                          // Fill matrix with random values between [-100, 100]
                          std::default_random_engine re{ std::random_device{}() };
                          std::uniform_int_distribution<int> dist{ -100, 100 };
                          std::for_each(std::begin(mtx), std::end(mtx),
                              [&dist, &re](auto& row) {
                                  std::for_each(std::begin(row), std::end(row),
                                      [&dist, &re](auto& n) { n = dist(re); }
                                  );
                              }
                          );
                      
                          auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints
                          
                          // Print matrix
                          std::cout << "mtx = ";
                          std::ranges::for_each(jv, [](auto n) { std::cout << n << " "; });
                          std::cout << "\n";
                      
                          // Sum all positive values in the matrix    
                          int sum{0};
                          std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });
                          std::cout << "sum = " << sum << "\n";
                      }
                      
                      int sum{0};
                      auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints
                      std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });
                      
                      auto sum{ std::ranges::accumulate(jv, 0, [](auto total, auto n) { return total + ((n > 0) ? n : 0); }) };
                      
                      #include <algorithm>  // for_each
                      #include <iostream>  // cout
                      #include <random>  // default_random_engine, uniform_int_distribution
                      #include <ranges>  // for_each, join_view
                      #include <vector>
                      
                      using matrix = std::vector<std::vector<int>>;
                      
                      int main()
                      {
                          matrix mtx{3, std::vector<int>(3)};
                      
                          // Fill matrix with random values between [-100, 100]
                          std::default_random_engine re{ std::random_device{}() };
                          std::uniform_int_distribution<int> dist{ -100, 100 };
                          std::for_each(std::begin(mtx), std::end(mtx),
                              [&dist, &re](auto& row) {
                                  std::for_each(std::begin(row), std::end(row),
                                      [&dist, &re](auto& n) { n = dist(re); }
                                  );
                              }
                          );
                      
                          auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints
                          
                          // Print matrix
                          std::cout << "mtx = ";
                          std::ranges::for_each(jv, [](auto n) { std::cout << n << " "; });
                          std::cout << "\n";
                      
                          // Sum all positive values in the matrix    
                          int sum{0};
                          std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });
                          std::cout << "sum = " << sum << "\n";
                      }
                      
                      int sum{0};
                      auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints
                      std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });
                      
                      auto sum{ std::ranges::accumulate(jv, 0, [](auto total, auto n) { return total + ((n > 0) ? n : 0); }) };
                      
                      #include <algorithm>  // for_each
                      #include <iostream>  // cout
                      #include <random>  // default_random_engine, uniform_int_distribution
                      #include <ranges>  // for_each, join_view
                      #include <vector>
                      
                      using matrix = std::vector<std::vector<int>>;
                      
                      int main()
                      {
                          matrix mtx{3, std::vector<int>(3)};
                      
                          // Fill matrix with random values between [-100, 100]
                          std::default_random_engine re{ std::random_device{}() };
                          std::uniform_int_distribution<int> dist{ -100, 100 };
                          std::for_each(std::begin(mtx), std::end(mtx),
                              [&dist, &re](auto& row) {
                                  std::for_each(std::begin(row), std::end(row),
                                      [&dist, &re](auto& n) { n = dist(re); }
                                  );
                              }
                          );
                      
                          auto jv{ std::ranges::join_view(mtx) };  // flatten mtx into a list of ints
                          
                          // Print matrix
                          std::cout << "mtx = ";
                          std::ranges::for_each(jv, [](auto n) { std::cout << n << " "; });
                          std::cout << "\n";
                      
                          // Sum all positive values in the matrix    
                          int sum{0};
                          std::ranges::for_each(jv, [&sum](auto n) { sum += ((n > 0) ? n : 0); });
                          std::cout << "sum = " << sum << "\n";
                      }
                      

                      Performance issue when using multiple threads with sqlite3

                      copy iconCopydownload iconDownload
                      int
                      sql_insert(SQL *sql, const char *filename, char unsigned hash[])
                      {
                          pthread_mutex_lock(&sql->mutex);
                          // ... actual insert and exec code ...
                          pthread_mutex_unlock(&sql->mutex);
                          return 0;
                      }
                      

                      Problem with type Point3f in function cv2.calibrateCamera PYTHON

                      copy iconCopydownload iconDownload
                      objpoints = np.array([objpoints], dtype = np.float32)
                      imgpoints = np.array([imgpoints], dtype = np.float32)
                      
                      objpoints = np.array(objpoints, dtype = np.float32)
                      imgpoints = np.array(imgpoints, dtype = np.float32)
                      
                      objpoints = np.array([objpoints], dtype = np.float32)
                      imgpoints = np.array([imgpoints], dtype = np.float32)
                      
                      objpoints = np.array(objpoints, dtype = np.float32)
                      imgpoints = np.array(imgpoints, dtype = np.float32)
                      
                      objpoints = np.array(objpoints, dtype = np.float32)[np.newaxis]
                      imgpoints = np.array(imgpoints, dtype = np.float32)[np.newaxis]
                      ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, imsize, None, None )
                      
                      objApoints = np.array(objApoints, dtype=np.float32)
                      img1points = np.array(img1points, dtype=np.float32)
                      
                      # have another picture? img2points...
                      # it may show the same object (objApoints) or a different object (objBpoints)
                      
                      objpointslist = [objApoints]
                      imgpointslist = [img1points]
                      
                      cv2.calibrateCamera(objpointslist, imgpointslist, ...)
                      

                      How to properly sync multithreading with mutex in c?

                      copy iconCopydownload iconDownload
                      void *
                      use_res(void *v) {
                       pthread_mutex_lock(&mtx);
                       struct count *p = (struct count *) v;
                       printf("--thread no %d :\n" p->no);
                       pthread_mutex_unlock(&mtx);
                       return NULL;
                      }
                      

                      Arithmetic operation using a conditional statement

                      copy iconCopydownload iconDownload
                      df <- within(df, {
                        P <- NA
                        P[phi == "Z1" & tal == "1-2"] <- n[phi == "Z1" & tal == "1-2"]/mtx[1, 1]
                        P[phi == "Z1" & tal == "3-4"] <- n[phi == "Z1" & tal == "3-4"]/mtx[1, 2]
                        P[phi == "Y2" & tal == "1-2"] <- n[phi == "Y2" & tal == "1-2"]/mtx[2, 1]
                      })
                      df
                      #   foo phi   tal   n          P
                      # 1   A  Z1   1-2 324 0.05415343
                      # 2   B  Z1   3-4 872 0.14574628
                      # 3   C  X3   5-6 163         NA
                      # 4   D  W4   7-8 953         NA
                      # 5   F  V5  9-10 453         NA
                      # 6   G  W4 11-12 943         NA
                      

                      Thread-safe locking of instance with multiple member functions

                      copy iconCopydownload iconDownload
                      #include <iostream>       // std::cout
                      #include <thread>         // std::thread
                      #include <mutex>          // std::mutex
                      
                      class information_t {
                      
                        private:
                          std::mutex mtx;
                          int importantValue = 0;
                      
                        public:
                          class Monitor {
                            private:
                              information_t& resource;
                              std::lock_guard<std::mutex> lock;
                          
                            friend class information_t; // to allow access to constructor.
                            
                            private:      
                              Monitor(information_t& resource):
                                resource(resource), lock(resource.mtx)
                              { }
                            public:
                              ~Monitor()
                              {
                                std::cout << "Result: " << resource.importantValue << '\n';
                                resource.reset();
                              }
                            
                              Monitor(const Monitor&) = delete; // copying prohibited
                              Monitor& operator=(const Monitor&) = delete; // copy assign prohibited
                          
                            public:
                              // exposed resource API for monitor owner:
                              void incrementIt() { resource.incrementIt(); }
                              void decrementIt() { resource.decrementIt(); }
                              void reset() { resource.reset(); }
                          };
                          friend class Monitor; // to allow access to private members
                        
                        public:
                          Monitor aquire() { return Monitor(*this); }
                          
                        private:
                          // These should only be callable from the thread that currently holds the mutex
                          // Hence, they are private and accessible through a monitor instance only
                          void incrementIt() { importantValue++; }
                          void decrementIt() { importantValue--; }
                          void reset() { importantValue = 0; }
                      
                      } protectedResource; // We only have one instance of this that we need to work with
                      
                      #if 0 // OBSOLETE
                      // Free the resource so other threads can reserve and use it
                      void release()
                      {
                          protectedResource.reset();
                          protectedResource.mtx.unlock(); // Will this work? Can I guarantee the mtx is locked?
                      }
                      #endif // 0
                      
                      // Supposed to make sure no other thread can reserve or use it now anymore!
                      information_t::Monitor reserve()
                      { 
                        return protectedResource.aquire();
                      }
                      
                      using MyResource = information_t::Monitor;
                      
                      int main()
                      {
                          std::thread threads[3];
                          
                          threads[0]
                            = std::thread([]
                              {
                                MyResource protectedResource = reserve();
                                protectedResource.incrementIt();
                                protectedResource.incrementIt();
                                // scope end releases protectedResource
                              });
                      
                          threads[1]
                            = std::thread([]
                              {
                                try {
                                  MyResource protectedResource = reserve();
                                  throw "Haha!";
                                  protectedResource.incrementIt();
                                  // scope end releases protectedResource
                                } catch(...) { }
                              });
                      
                          threads[2]
                            = std::thread([]
                              {
                                MyResource protectedResource = reserve();
                                protectedResource.decrementIt();
                                  // scope end releases protectedResource
                              });
                      
                          for (auto& th : threads) th.join();
                      
                          return 0;
                      }
                      
                      Result: 2
                      Result: -1
                      Result: 0
                      
                      #include <iostream>       // std::cout
                      #include <thread>         // std::thread
                      #include <mutex>          // std::mutex
                      
                      class information_t {
                      
                        private:
                          std::mutex mtx;
                          int importantValue = 0;
                      
                        public:
                          class Monitor {
                            private:
                              information_t& resource;
                              std::lock_guard<std::mutex> lock;
                          
                            friend class information_t; // to allow access to constructor.
                            
                            private:      
                              Monitor(information_t& resource):
                                resource(resource), lock(resource.mtx)
                              { }
                            public:
                              ~Monitor()
                              {
                                std::cout << "Result: " << resource.importantValue << '\n';
                                resource.reset();
                              }
                            
                              Monitor(const Monitor&) = delete; // copying prohibited
                              Monitor& operator=(const Monitor&) = delete; // copy assign prohibited
                          
                            public:
                              // exposed resource API for monitor owner:
                              void incrementIt() { resource.incrementIt(); }
                              void decrementIt() { resource.decrementIt(); }
                              void reset() { resource.reset(); }
                          };
                          friend class Monitor; // to allow access to private members
                        
                        public:
                          Monitor aquire() { return Monitor(*this); }
                          
                        private:
                          // These should only be callable from the thread that currently holds the mutex
                          // Hence, they are private and accessible through a monitor instance only
                          void incrementIt() { importantValue++; }
                          void decrementIt() { importantValue--; }
                          void reset() { importantValue = 0; }
                      
                      } protectedResource; // We only have one instance of this that we need to work with
                      
                      #if 0 // OBSOLETE
                      // Free the resource so other threads can reserve and use it
                      void release()
                      {
                          protectedResource.reset();
                          protectedResource.mtx.unlock(); // Will this work? Can I guarantee the mtx is locked?
                      }
                      #endif // 0
                      
                      // Supposed to make sure no other thread can reserve or use it now anymore!
                      information_t::Monitor reserve()
                      { 
                        return protectedResource.aquire();
                      }
                      
                      using MyResource = information_t::Monitor;
                      
                      int main()
                      {
                          std::thread threads[3];
                          
                          threads[0]
                            = std::thread([]
                              {
                                MyResource protectedResource = reserve();
                                protectedResource.incrementIt();
                                protectedResource.incrementIt();
                                // scope end releases protectedResource
                              });
                      
                          threads[1]
                            = std::thread([]
                              {
                                try {
                                  MyResource protectedResource = reserve();
                                  throw "Haha!";
                                  protectedResource.incrementIt();
                                  // scope end releases protectedResource
                                } catch(...) { }
                              });
                      
                          threads[2]
                            = std::thread([]
                              {
                                MyResource protectedResource = reserve();
                                protectedResource.decrementIt();
                                  // scope end releases protectedResource
                              });
                      
                          for (auto& th : threads) th.join();
                      
                          return 0;
                      }
                      
                      Result: 2
                      Result: -1
                      Result: 0
                      

                      See all related Code Snippets

                      Community Discussions

                      Trending Discussions on MTX
                      • Accept and return lambda (lock wrapper)
                      • Camera calibration, focal length value seems too large
                      • Why does Condvar thread never wake up?
                      • Audio matlab challenge: Reverberation, FDN, Filtering
                      • Multithreaded server don't switch between threads cpp
                      • How I can run two threads parallelly one by one?
                      • How to use std::acumulate for matrix
                      • Performance issue when using multiple threads with sqlite3
                      • Problem with type Point3f in function cv2.calibrateCamera PYTHON
                      • How to properly sync multithreading with mutex in c?
                      Trending Discussions on MTX

                      QUESTION

                      Accept and return lambda (lock wrapper)

                      Asked 2022-Mar-17 at 18:14

                      I want to accept any lambda, so that it can perform some operation safely under the lock_guard and then return anything, but using as shown below throws an error:

                      #include <iostream>
                      #include <functional>
                      #include <mutex>
                      #include <memory>
                      
                      class Test {
                          public:
                              template<typename Ret>
                              Ret DoLocked(std::function<Ret(Test&)> func) {
                                  std::lock_guard<std::mutex> lock(*mtx);
                                  return func(*this);
                              }
                          private:
                              std::unique_ptr<std::mutex> mtx = std::make_unique<std::mutex>();
                      };
                      
                      int main() {
                          Test a;
                          a.DoLocked([](Test &s) {
                              std::cout << "in do locked" << std::endl;
                          });
                      
                          return 0;
                      }
                      
                      [build] /some-path/test.cc:21:6: error: no matching function for call to ‘Test::DoLocked(main()::<lambda(Test&)>)’
                      [build]    21 |     });
                      [build]       |      ^
                      [build] /some-path/test.cc:9:13: note: candidate: ‘template<class Ret> Ret Test::DoLocked(std::function<Ret(Test&)>)’
                      [build]     9 |         Ret DoLocked(std::function<Ret(Test&)> func) {
                      [build]       |             ^~~~~~~~
                      [build] /some-path/test.cc:9:13: note:   template argument deduction/substitution failed:
                      [build] /some-path/test.cc:21:6: note:   ‘main()::<lambda(Test&)>’ is not derived from ‘std::function<Ret(Test&)>’
                      [build]    21 |     });```
                      

                      ANSWER

                      Answered 2022-Mar-17 at 18:14

                      This is easily solved by getting rid of std::function and making the function parameter a template parameter. That would look like

                      template<typename Func>
                      auto DoLocked(Func func) -> decltype(func(*this)) {
                          std::lock_guard<std::mutex> lock(*mtx);
                          return func(*this);
                      }
                      

                      The reason it doesn't work with the std::function is that a lambda expression does not create a std::function. It creates a object of an unnamed class type that has an operator() defined with the body of the lambda expression. Because of this, template deduction fails as it is expecting a std::function but that is not what is being provided.

                      Source https://stackoverflow.com/questions/71517035

                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                      Vulnerabilities

                      No vulnerabilities reported

                      Install MTX

                      You can download it from GitHub.
                      You can use MTX like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the MTX component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

                      Support

                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

                      DOWNLOAD this Library from

                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      Explore Related Topics

                      Share this Page

                      share link
                      Consider Popular Game Engine Libraries
                      Compare Game Engine Libraries with Highest Support
                      Compare Game Engine Libraries with Highest Quality
                      Compare Game Engine Libraries with Highest Security
                      Compare Game Engine Libraries with Permissive License
                      Compare Game Engine Libraries with Highest Reuse
                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.