Posts

Showing posts from 2023

Parallel Comparison of C++ and Ada Producer-Consumer Implementations

  Producer Consumer Comparison  The C++ source code for this example is taken from the blog post here by Andrew Wei. A detailed description of the C++ software is given in the blog post. This solution is shown in parallel with a corresponding Ada solution. Both C++ and Ada separate interface specifications from implementation. C++ uses the header file, in this case the file named Buffer.hpp, to provide the interface specification for the buffer used in this example. C++ is not very strict about what goes into a header file and what goes into a .cpp file. The Ada version creates an Ada package. The Ada package specification defines the task types named producer_Int and consumer_Int. The buffer shared by all instances of producer_int and consumer_int is defined within the Ada package body file. Interface Specification Files Ada C++ package pc_tasks is task type produce_Int (Id : Natural); task type consume_Int (Id : Natura...

Parallel Comparison of Java Producer-Consumer with Ada Producer-Consumer

  Comparison of Java producer-consumer source code with Ada producer-consumer source code. While the Java program defines several classes the Ada program defines one Ada package and a main procedure. The Ada package encapsulates the definitions of the shared buffer type and the task types. The main procedure creates instances of the shared buffer type and the task types. Ada packages separate interface definitions from implementation. In this example the interface definition and the definition are split into two files, which Ada calls the package specification and the package body. The Shared buffer Both programs implement a producer-consumer model using a single-element buffer shared by the producer and the consumer. Both programs implement a shared buffer object with two data elements. A count is stored in a variable named materials and a  Boolean variable named available is used to control access to the shared buffer by the producer and consumer thread (or ta...

Alternative to exceptions when attempting to pop an empty stack

  A recent question on StackOverflow asked about whether or not a mutex is locked twice by the same thread without unlocking the mutex. See https://stackoverflow.com/questions/76890110/c-the-thread-repeatedly-locks-the-same-mutex-multiple-times?noredirect=1#comment135552146_76890110 The C++ source code presented in the question is: 1 #include <exception> 2 #include <memory> 3 #include <mutex> 4 #include <stack> 5 6 struct empty_stack : std :: exception 7 { 8     const char * what () const throw (); 9 }; 10 11 template < typename T > 12 class threadsafe_stack 13 { 14 private : 15     std :: stack < T > data ; 16     mutable std :: mutex m ; 17 public : 18     threadsafe_stack (){} 19     threadsafe_stack ( const threadsafe_stack & other ) { 20        std :: lock_guard < std :: mutex > lock ( other . m ); 21    ...