Linear System in C++

Linear System Solutions in C++ using Boost::ublas

#include < boost/numeric/ublas/matrix.hpp > #include < boost/numeric/ublas/lu.hpp > #include < boost/numeric/ublas/io.hpp > using namespace boost::numeric::ublas; using namespace std; typedef boost::numeric::ublas::vector< double > ublasVector; typedef boost::numeric::ublas::matrix< double > ublasMatrix; typedef boost::numeric::ublas::matrix_row< ublasMatrix > ublasMatrixRow; typedef boost::numeric::ublas::matrix_range< matrix < double > > ublasMatrixRange;

Gaussian Elimination Method

// Ax=b ==>> transform to Ux=b ublasVector GaussianElimination(ublasMatrix um, ublasVector uv) { std::cout << uv << std::endl; std::cout << um << std::endl; // eliminate and create upper triangle augmented matrix for(int i=0; i<(uv.size()-1); ++i){ for(int j=i+1; j< uv.size(); ++j){ double lem=um(j,i)/um(i,i); ublasMatrixRow(um,j) -= lem*ublasMatrixRow(um,i); uv(j)-=lem*uv(i); } } // back substitution to get result for(int i=uv.size()-1; i>=0; --i){ double in=inner_prod(subrange(uv,i+1,uv.size()),subrange(ublasMatrixRow(um,i),i+1,uv.size())); uv(i)=(uv(i)-in)/um(i,i); } ublasVector retuv(uv); return retuv; }

LU Decomposition

// decompose Ax=b ==>> LUx=b hance tranform A=LU void LUDecomposition(ublasMatrix& um) { std::cout << um << std::endl; for(int i=0; i< (um.size1()-1); ++i){ for(int j=i+1; j< um.size1(); ++j){ double lem=um(j,i)/um(i,i); ublasMatrixRange(um,range(j,j+1),range(i+1,um.size1())) -= lem*ublasMatrixRange(um,range(i,i+1),range(i+1,um.size1())); um(j,i)=lem; } } }

LU Solver using LUDecomposition

// This use LUdecompose matrix to resolve liner equation ublasVector LUSolver(ublasMatrix um, ublasVector uv) { // forward substitution Ly=b to get solution for y for(int i=1; i< uv.size(); ++i){ double in=inner_prod(subrange(ublasMatrixRow(um,i),0,i),subrange(uv,0,i)); uv(i)-=in; } // back substitution to get result Ux=y for(int i=uv.size()-1; i>=0; --i){ double in=inner_prod(subrange(uv,i+1,uv.size()),subrange(ublasMatrixRow(um,i),i+1,uv.size())); uv(i)=(uv(i)-in)/um(i,i); } ublasVector retuv(uv); return retuv; }

Test Programs

void testLUDecompose() { ublasVector uv (3); uv (0) = 6;uv (1) = 3;uv (2) = 7; ublasMatrix um(3,3); um(0,0)=3;um(0,1)=-1;um(0,2)=4; um(1,0)=-2;um(1,1)=0;um(1,2)=5; um(2,0)=7;um(2,1)=2;um(2,2)=-2; std::cout << um << std::endl; LUDecomposition(um); std::cout << um << std::endl; // calculate determinante |A| double dt=1; for(int i=0; i< um.size1();++i) dt*=um(i,i); std::cout << dt << std::endl; ublasVector retuv=LUSolver(um,uv); std::cout << retuv << std::endl; }

Choleski Decomposition Method

// decompose Ax=b ==>> L*trans(L)x=b void CholeskiDecomposition(ublasMatrix& um) { std::cout << um << std::endl; for(int i=0; i< um.size1(); ++i){ try{ ublasVector uv=subrange(ublasMatrixRow(um,i),0,i); double in = inner_prod(uv,uv); if(in < um(i,i)) um(i,i)=sqrt(um(i,i)-inner_prod(uv,uv)); else cout<< "Matirx is not positive definite" << endl; // throw exception here for(int j=i+1; j< um.size1(); ++j){ double in = inner_prod(subrange(ublasMatrixRow(um,i),0,i),subrange(ublasMatrixRow(um,j),0,i)); um(j,i) = (um(j,i) - in)/um(i,i); } } for(int i=1; i< um.size1(); ++i) { ublasMatrixRange(um,range(0,i),range(i,i+1))=zero_matrix(i,1); } }

void testCholeski() { ublasMatrix um1(3,3); um1(0,0)=4;um1(0,1)=-2;um1(0,2)=1; um1(1,0)=-2;um1(1,1)=4;um1(1,2)=-2; um1(2,0)=1;um1(2,1)=-2;um1(2,2)=4; std::cout << um1 << std::endl; CholeskiDecomposition(um1); std::cout << um1 << std::endl; ublasMatrix umt=trans(um1); std::cout << umt << std::endl; std::cout << prod(um1,umt) << std::endl; }

PThreads Primer

PThreads Primer

This is from PThreads Primer book by Bil Lewis, Daniel J. Berg

Concurrency means that two or more threads can be in the middle of executing code at the same time; it could be the same code, it could be different code. They may or may not be actually executing at the same time, but they are in the middle of it.
Parallelism means that two or more threads actually run at the same time on different CPUs.
A system call is basically a function that ends up trapping to routines in the kernel. we divide system calls into two categories, blocking and nonblocking calls (aka synchronous and asynchronous I/O).
Signals are the UNIX kernel's way of interrupting a running process and letting it know that something of interest has happened.
Synchronization is the method of ensuring that multiple threads coordinate their activities so that one thread doesn't accidently change data that another thread is working on.
Scheduling is the act of placing threads onto CPUs, so that they can execute, and of taking them off of those CPUs so that others can run instead.
Process structure used to contain the memory map, the signal dispatch table, signal mask, user ID, group ID, working directory, etc., along with runtime statistics, CPU state (registers, etc.), and a kernel stack (for executing system calls). A nonblocking system call may send the process a signal to tell it that the call is completed.
Threads are a method of allowing concurrent execution in a single address space. Threads allow parallel execution on multiple processor machines.
Threads own stack and stack pointer; a program counter; some thread information,
When a process makes a system call, the following events occur: 1. The process traps to the kernel. 2. The trap handler runs in kernel mode, and saves all of the registers. 3. It sets the stack pointer to the process structure's kernel stack. 4. The kernel runs the system call. 5. The kernel places any requested data into the user-space structure that the programmer provided. 6. The kernel changes any process structure values affected. 7. The process returns to user mode, replacing the registers and stack pointer, and returns the appropriate value from the system call.
such as scheduling priority, and signal mask, stored in the thread structure; and the CPU registers (the stack pointer and program counter are actually just registers).
Signals are the mechanism that UNIX uses in order to get asynchronous behavior in a program9. How this works in non-threaded programs is this: Your program is running along normally, minding its own business. Then something (another process or the kernel) sends a signal to your process. The kernel then stops your process in its tracks, and forces it to run some other function (it is probably one you have written). That function runs, doing whatever it wants, then it can either return (and your program will then resume right where it left off), or it can do a siglongjmp() (in which case your program resumes at the sigsetjmp() location), or it can just call exit() (causing the entire process to exit).
When a process makes a system call, the following events occur: 1. The program will call sigaction() to declare some function to be the handler for a given signal (say, function foo() will handle SIGUSR1). The kernel will put a pointer to that handler into the process structurefs signal dispatch table. 2. Next, your program will call sigprocmask() to tell the kernel which signals it is willing to accept (here, SIGUSR1, yes; SIGUSR2, no). 3. Finally your program takes off and starts doing what you wrote it to do. 4. Now, when some other process sends your process SIGUSR1, your program will stop what it's doing... 5. and run the handler code you wrote. You have no idea what your program might be doing when the signal arrives. That's the idea with signals, they can be completely asynchronous. 6. When the signal handler is done, it typically just does a return, and your program continues where it left off, as if nothing had happened.
detached thread : intend not to join a thread nondetached thread : intend to do a join
The main thread is always a nondetached thread, so it can be joined
detached thread will clean up after itself upon exit, returning its thread structure, TSD array, and stack to the heap for reuse. A nondetached thread will clean up after itself only after it has been joined1.
pthread_detach: dynamically change the detach status
When any thread falls off the bottom of its initial function, it implicitly calls pthread_exit(), exiting only that one thread. pthread_cancel :one thread to tell another thread to exit. pthread_self() : to return the thread ID thread_name(tid) : to produce a printable string for the TID2
Time Sliced Scheduling Strict Priority Scheduling
cause to context switch. Synchronization. got lock on resource. [devloper control] Preemption. some another higer priority thread runnable [devloper control] Yielding. sched_yield() [devloper control] Time-Slicing. system does time slicing.[system-vendor control]
Thread state Active, Runnable, Sleeping[lock], Zombie
realtime tricks?meaning no blocking system calls, probably no I/O8, no paging (you'll need to lock down all the memory that your thread will use: functions, stack, data.)
SCHED_FIFO : There is no time slicing and threads never change their priorities(unless the programmer makes a call to pthread_setschedparam()). SCHED_RR : This is much the same as SCHED_FIFO, save that there is time slicing and threads rotate in their queues. SCHED_OTHER : POSIX puts no limits on the behavior of this option
four aspects of scheduling attributes Scope: pthread_attr_setscope() allows you to select either PTHREAD_SCOPE_PROCESS (local scheduling, unbound threads) or PTHREAD_SCOPE_SYSTEM (global scheduling, bound threads). Policy : pthread_attr_setschedpolicy() allows you to select SCHED_RR, SCHED_FIFO, or SCHED_OTHER, or other implementation-defined policies. Priority : pthread_attr_setschedparam() allows you to set the priority level of a thread by setting the sched_param struct element param.sched_priority. Inheritance : pthread_setinheritsched() allows you to specify if the scheduling policy and parameters will be inherited from the creating thread (PTHREAD_INHERIT_SCHED), or will be set directly by the other functions (PTHREAD_EXPLICIT_SCHED).
Implementation of synchronization requires the existence of an atomic test and set instruction in hardware.
A critical section is a section of code that must be allowed to complete atomically with no interruption that affects its completion.
There are two basic things you want to do. Thing one is that you want to protect shared data. This is what locks do. Thing two is that you want to prevent threads from running when there's nothing for them to do. You don't want them spinning, wasting time. This is what semaphores, condition variables, join, barriers, etc. are for.
Mutexes The mutual exclusion lock.pthread_mutex_lock() and pthread_mutex_unlock().
pthread_mutex_trylock() returns 0 if you get the lock, and EBUSY if you don't. If you get EBUSY, you'll have to figure out something else to do, as entering the critical section anyway would be highly antisocial.
counting semaphore is a variable that you can increment[sem_post] arbitrarily high, but decrement[sem_wait] only to zero.
POSIX semaphores are unique among synchronization variables in one particular fashion: They are async safe, meaning that it is legal to call sem_post() from a signal handler. No other synchronization variable is async safe. So, if you want to write a signal handler that causes some other thread to wake up, this is the way to do it.


Command Design Pattern C++

Command Design Pattern

// Parameter should contain in type T // if need to use different signature for function pointer use function and bind from Boost. // use union concept and make this can work with function pointer vs class member function pointer.
template <typename T> class command { public: // class member function pointer typedef void(T::*Action)(); Command(T *object=0, Action method=0){ m_object = object; m_method = method; } void execute() { (m_object->*m_method)(); }
// now decide as per your domain //is this copyable or movable or none
private: T *m_object; Action m_method; }

Brainteaser list from Wilmott FAQ

Brainteaser

Referance from Wilmott FAQ
1. Russian Roulette : 1/3,1/4,1/3,1/2,fatel
2. Matching Birthday : Think who's bday don't match 364!/(364-n)!365^n

Boost uBlas Matrix

Matrix overview
The templated class matrix is the base container adaptor for dense matrice
Header : <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> void ublas2matrix() { using namespace boost::numeric::ublas; matrix m (3, 3); for (unsigned i = 0; i < m.size1 (); ++ i) // row for (unsigned j = 0; j < m.size2 (); ++ j) // column m (i, j) = 3 * i + j; // opertor(i,j) std::cout << m << std::endl; m.erase_element(1,1); m.erase_element(1,2); std::cout << m << std::endl; m.clear(); std::cout << m << std::endl;
//identity_matrix
identity_matrix im (3); std::cout << im << std::endl;
//zero_matrix
zero_matrix zm (3); std::cout << zm << std::endl;
//scalar_matrix
int val=20; scalar_matrix sm (3,3,val); // default val=1 std::cout << sm << std::endl; }
Triangular Matrix

Example code link
#include <boost/numeric/ublas/triangular.hpp> void ublas3matrix() { using namespace boost::numeric::ublas; matrix m (3, 3); for (unsigned i = 0; i < m.size1 (); ++ i) // row for (unsigned j = 0; j < m.size2 (); ++ j) // column m (i, j) = 3 * i + j; // opertor(i,j) std::cout << "full matrix = " << m << "\n" ; triangular_matrix < double, lower> L=triangular_adaptor< matrix < double >, lower> (m); triangular_matrix < double, unit_lower> UL=triangular_adaptor< matrix < double >, unit_lower> (m); triangular_matrix < double, strict_lower> SL=triangular_adaptor< matrix < double >, strict_lower> (m); std::cout << "lower L = " << L << "\n" << "strict lower SL = " << SL << "\n" << "unit lower UL = " << UL << "\n" ; triangular_matrix < double, upper> U = triangular_adaptor< matrix < double >, upper> (m); triangular_matrix < double, unit_upper> UU = triangular_adaptor < matrix < double >, unit_upper> (m); triangular_matrix < double, strict_upper> SU=triangular_adaptor < matrix < double >, strict_upper> (m); std::cout << "upper U = " << U << "\n" << "strict upper SU = " << SU << "\n" << "unit upper UU = " << UU << "\n" ; }

Symmetric Matrix
#include <boost/numeric/ublas/symmetric.hpp> void ublas4matrix() { using namespace boost::numeric::ublas; symmetric_matrix ml (3, 3); std::cout << ml << std::endl; for (unsigned i = 0; i < ml.size1 (); ++ i) for (unsigned j = 0; j < ml.size2(); ++ j) ml (i, j) = rand()%20; std::cout << ml << std::endl; symmetric_matrix mu (3, 3); std::cout << mu << std::endl; for (unsigned i = 0; i < mu.size1 (); ++ i) for (unsigned j = 0; j < mu.size2 (); ++ j) mu (i, j) = rand()%30; std::cout << mu << std::endl; std::cout << "=====================================================" << std::endl; matrix m (3, 3); symmetric_adaptor< matrix , lower> sal (m); for (unsigned i = 0; i < sal.size1 (); ++ i) for (unsigned j = 0; j < sal.size2(); ++ j) sal (i, j) = rand()%20; std::cout << sal << std::endl; symmetric_adaptor< matrix , upper> sau (m); for (unsigned i = 0; i < sau.size1 (); ++ i) for (unsigned j = 0; j < sau.size2 (); ++ j) sau (i, j) = rand()%30; std::cout << sau << std::endl; }

Hermitian matrix

Hermitian matrix (or self-adjoint matrix) is a square matrix with complex entries that is equal to its own conjugate transpose – that is, the element in the i-th row and j-th column is equal to the complex conjugate of the element in the j-th row and i-th column, for all indices i and j:

#include <boost/numeric/ublas/hermitian.hpp> void ublas5matrix () { using namespace boost::numeric::ublas; hermitian_matrix< std::complex < double >, lower > ml (3, 3); for (unsigned i = 0; i < ml.size1 (); ++ i) { for (unsigned j = 0; j < i; ++ j) ml (i, j) = std::complex < double> (rand()%3, 3 * i + j); ml (i, i) = std::complex < double> (rand()%4, 0); } std::cout << ml << std::endl; hermitian_matrix< std::complex < double>, upper> mu (3, 3); for (unsigned i = 0; i < mu.size1 (); ++ i) { mu (i, i) = std::complex (4 * i, 0); for (unsigned j = i + 1; j < mu.size2 (); ++ j) mu (i, j) = std::complex < double> (rand()%5, rand()%j); } std::cout << mu << std::endl; std::cout << "=====================================================" << std::endl; matrix< std::complex < double> > m (3, 3); hermitian_adaptor< matrix < std::complex < double> >, lower> hal (m); for (unsigned i = 0; i < hal.size1 (); ++ i) { for (unsigned j = 0; j < i; ++ j) hal (i, j) = std::complex< double> (3 * i + j, 3 * i + j); hal (i, i) = std::complex< double> (4 * i, 0); } std::cout << hal << std::endl; hermitian_adaptor< matrix < std::complex < double> >, upper> hau (m); for (unsigned i = 0; i < hau.size1 (); ++ i) { hau (i, i) = std::complex (4 * i, 0); for (unsigned j = i + 1; j < hau.size2 (); ++ j) hau (i, j) = std::complex (3 * i + j, 3 * i + j); } std::cout << hau << std::endl; }


STL Algorithm - I

STL Algorithm cheetsheet-I
This is only for notedown syntax, how to use particuler algorithm. This has taken referance from www.cplusplus.com
for_each : Apply function to range
void myforeach(int& i){i=rand();} void testforeach() { vector< int > intvec(10); copy(intvec.begin(),intvec.end(),ostream_iterator< int >(cout,",")); cout << std::endl; for_each(intvec.begin(),intvec.end(),&myforeach); copy(intvec.begin(),intvec.end(),ostream_iterator< int >(cout,",")); cout << std::endl; }
find : Find value in range
void myforeach(int& m){static int i=0;m=++i;} void testfind() { vector< int > intvec(10); for_each(intvec.begin(),intvec.end(),&myforeach); copy(intvec.begin(),intvec.end(),ostream_iterator< int >(cout,","));cout<::iterator it=find(intvec.begin(),intvec.end(),11); if(it!=intvec.end()) cout << "Value found\n"; else cout << "Value not found\n"; }
find_if : Find element in range
Returns an iterator to the first element in the range [first,last) for which applying pred to it, is true.
void myforeach(int& m){static int i=0;m=++i;} bool IsOdd (int i) { return ((i%2)==1);} void testfindif() { vector intvec(10); for_each(intvec.begin(),intvec.end(),&myforeach); copy(intvec.begin(),intvec.end(),ostream_iterator(cout,","));cout<::iterator it=find_if(intvec.begin(),intvec.end(),&IsOdd); if(it!=intvec.end()) cout << "Value found\n"; else cout << "Value not found\n"; }
count :Count appearances of value in range
Returns the number of elements in the range [first,last) that compare equal to value
void myforeach(int& m){static int i=0;m=(++i)%2;} void testcount() { vector< int > intvec(10); for_each(intvec.begin(),intvec.end(),&myforeach); copy(intvec.begin(),intvec.end(),ostream_iterator< int >(cout,","));cout << std::endl; int iCount=(int)count(intvec.begin(),intvec.end(),1); cout << "Number of element count " << iCount << std::endl; }
count_if : Return number of elements in range satisfying condition
Returns the number of elements in the range [first,last) for which condition pred is true.
void myforeach(int& m){static int i=0;m=(++i);} bool IsOdd (int i) { return ((i%2)==1);} void testcount() { vector< int > intvec(10); for_each(intvec.begin(),intvec.end(),&myforeach); copy(intvec.begin(),intvec.end(),ostream_iterator< int >(cout,","));cout << std::endl; int iCount=(int)count_if(intvec.begin(),intvec.end(),&IsOdd); cout << "Number of element count " << iCount << std::endl; }
transform : Apply function to range
The first version applies op to all the elements in the input range ([first1,last1)) and stores each returned value in the range beginning at result. The second version uses as argument for each call to binary_op one element from the first input range ([first1,last1)) and one element from the second input range (beginning at first2).
transform (input.begin(), input.end(), result.begin(), unaryfun); transform (input1.begin(), input1.end(), input2.begin(), result.begin(), binaryfun);

copy : Copy range of elements
Copies the elements in the range [first,last) into a range beginning at result.
copy(input.begin(), input.end(), result.begin()); copy(input.begin(),input.end(),ostream_iterator(cout,","); copy(ifstream_iterator(ifile),ifstream_iterator(),back_inserter(mylist));

swap : Exchange values of two objects
Assigns the content of a to b and the content of b to a.
//Exchange values of two objects swap(avec,bvecc); /* swap_ranges Exchange values of two ranges Swaps the values of each of the elements in the range [first1,last1) with those of their respective elements in the range beginning at first2. */ swap_ranges(first.begin(), first.end(), second.begin());

fill : Fill range with value
Sets value to all elements in the range [first,last).
// scaler value fill fill(first.begin(), first.end(), value); // scaler value to range n element fill_n((first.begin(), nelem, value);

generate : Generate values for range with function
Sets value to all elements in the range [first,last).
int uid(){static int uid=rand()%10; return uid+=(rand()%10);} void testgen() { vector first(20); // generate Generate values for range with function generate(first.begin(), first.end(), &uid); // generate_n Generate values for sequence with function generate_n((first.begin(), nelem, &uid); }

remove : Remove value from range
Compares the elements in the range [first,last) against value, and removes those that compare equal from the resulting range. The resulting range consists of the elements between first and the iterator returned by the function, which points to the new end of the range.
int uid(){static int i=0; return ++i;}// unary function bool IsOdd(int &i){return ((i%2)==1);}// predicate void testremove() { vector first(20); generate(first.begin(), first.end(), &uid); // remove Remove value from range remove(first.begin(), first.end(), 3); //remove_if Remove elements from range remove_if(first.begin(), first.end(), IsOdd); }


Boost uBlas Vector

Vector overview
Header : #include <boost/numeric/ublas/vector.hpp> Header for ublas IO : #include <boost/numeric/ublas/io.hpp> unit_vector v (nelem, upos); upos element has 1, nelem number of element in vector zero_vector v (nelem); zero vector with nelem size scalar_vector v (nelem); scalar vector with nelem element all have value 1. boost::numeric::ublas::vector v (3); elements can be modified. sparse vectors : still don't understood compeletly, for time being added for future referance. Header : #include mapped_vector v (nelem); compressed_vector v (nelem, 3); coordinate_vector v (3, 3); got some compilation error
void testvector() // this can work for both vector and sparse vectors. { using namespace boost::numeric::ublas; mapped_vector v (3, 3); std::cout << v << std::endl; for (int i = 0; i < v.size(); ++i) { v(i)=i; } std::cout << v << std::endl; }
Vector Proxies
Header : <boost/numeric/ublas/vector_proxy.hpp>
void testVectorProxy() { using namespace boost::numeric::ublas; boost::numeric::ublas::vector v (5);
// The templated class vector_range allows addressing a sub-range of a vector's element. //The free subrange functions support the construction of vector ranges. //The free project functions support the construction of vector ranges.
std::cout << v << std::endl; //vector_range > vr(v,range(2,4)); //vector_range > vr =subrange(v, 2, 4); vector_range > vr =project(v, range(2, 4)); for (unsigned i = 0; i < vr.size (); ++ i) vr (i) = i*5+5; std::cout << vr << "\t" << vr.start() << std::endl; std::cout << v << std::endl; std::cout <<"============================================="<< std::endl;
// The templated class vector_slice allows addressing a slice of a vector. //The free subslice functions support the construction of vector slices. //The free project functions support the construction of vector slices
std::cout << v << std::endl; //vector_slice > vs (v, slice (0, 1, 3)); //vector_slice > vs = subslice(v,0,1,2); vector_slice > vs = project(v,slice(0,1,2)); for (unsigned i = 0; i < vs.size (); ++ i) vs (i) = i; std::cout << vs << std::endl; std::cout << v << std::endl; }
Vector Expressions
void testVectorExpressions() { using namespace boost::numeric::ublas; boost::numeric::ublas::vector > v (3); for (unsigned i = 0; i < v.size (); ++ i) v (i) = std::complex (i*7, i*2);
//The templated class vector_expression is required to be a public base of all classes which model the Vector Expression concept. //operator - computes the additive inverse of a vector expression. conj computes the complex conjugate of a vector expression. real and imag compute the real and imaginary parts of a vector expression. trans computes the transpose of a vector expression. herm computes the hermitian, i.e. the complex conjugate of the transpose of a vector expression.
std::cout << - v << std::endl; std::cout << conj (v) << std::endl; std::cout << real (v) << std::endl; std::cout << imag (v) << std::endl; std::cout << trans (v) << std::endl; std::cout << herm (v) << std::endl; std::cout <<"============================================="<< std::endl;
//operator + computes the sum of two vector expressions. operator - computes the difference of two vector expressions. v1.size==v2.size otherwise throw exception
boost::numeric::ublas::vector v1 (3), v2 (3); for (unsigned i = 0; i < std::min (v1.size (), v2.size ()); ++ i) v1 (i) = v2 (i) = i; std::cout << v1 << std::endl; std::cout << v2 << std::endl; std::cout << v1 + v2 << std::endl; std::cout << v1 - v2 << std::endl; std::cout <<"============================================="<< std::endl;
//outer_prod computes the outer product of two vector expressions.
std::cout << outer_prod (v1, v2) << std::endl;
//inner_prod computes the inner product of the vector expressions. prec_inner_prod computes the double precision inner product of the vector expressions.inner_prod (v1, v2) = sum (v1 [i] * v2 [i])
std::cout << inner_prod (v1, v2) << std::endl; std::cout << prec_inner_prod (v1, v2) << std::endl; std::cout <<"============================================="<< std::endl;
//operator * computes the product of a scalar and a vector expression. operator / multiplies the vector with the reciprocal of the scalar. 2.0/v1 not allowed.
std::cout << v1 / 2.0 << std::endl; std::cout << 2.0 * v1 << std::endl; std::cout <<"============================================="<< std::endl; boost::numeric::ublas::vector v3 (3); for (unsigned i = 0; i < v3.size (); ++ i) v3 (i) = i*2.2; std::cout << v3 << std::endl; std::cout << sum (v3) << std::endl;
// sum v = sum (v [i])
std::cout << norm_1 (v3) << std::endl;
// norm_1 v = sum (abs (v [i]))
std::cout << norm_2 (v3) << std::endl;
// norm_2 v = sqrt (sum (v [i] * v [i]))
std::cout << norm_inf (v3) << std::endl;
// norm_inf v = max (abs (v [i])
std::cout << index_norm_inf (v3) << std::endl;
// index_norm_inf v = min (i: abs (v [i]) == max (abs (v [i])))
}

Process scheduling in POSIX

Process Schudling

POSIX, processes run with a particular scheduling policy and associated scheduling attributes. Both the policy and the attributes can be changed independently. POSIX defines three policies: 1. SCHED_FIFO : Preemptive, priority-based scheduling.untill process not blocked. 2. SCHED_RR : Preemptive, priority-based scheduling with quanta. 3. SCHED_OTHER : An implementation-defined scheduler. Header file #include <sched.h> macro should defined _POSIX_PRIORITY_SCHEDULING

Process scheduling APIs
sched_getscheduler—Retrieve scheduling algorithm for a particular purpose. int sched_getscheduler(pid_t pid); if pid=0 then return scheduler of calling process. sched_setscheduler—Set scheduling algorithm/parameters for a process. int sched_setscheduler(pid_t pid, int policy, const struct sched_param *p); sched_get_priority_max—Get maximum priority value for a scheduler. int sched_get_priority_max(int alg); sched_get_priority_min — Get minimum priority value for a scheduler. int sched_get_priority_min(int alg); sched_getparam—Retrieve scheduling parameters for a particular process. int sched_getparam(pid_t pid, struct sched_param *p); sched_setparam — Set scheduling parameters for a process. int sched_setparam(pid_t pid, const struct sched_param *p); sched_yield — Yield the processor.sched_yield, when called, causes the calling process to give up its processor, and move to the back of the queue for its priority. int sched_yield(); sched_rr_get_interval—Get the SCHED_RR interval for the named process. int sched_rr_get_interval(pid_t pid, struct timespec *t);


Shared Memory and mapping in POSIX

Shared Memory
shared memory mapped into the process's address space with mmap, and unmapped with munmap. header #include <sys/mman.h> macro should defined _POSIX_SHARED_MEMORY Shared memory objects are created with a size of zero. They are sized using ftruncate and mapped in using mmap. The descriptor returned by this call is only useful for those functions int shm_unlink(char *shm_name); int shm_open(char *shm_name, int oflags, mode_t mode); int close(int fd);

Memory Mapping
The mmap function creates a virtual memory mapping for a region of the file fd. This mapping allows you to refer to the contents of the file as if it were memory. mmap—Map a shared memory object (or possibly another file) into process's address space. void *mmaps(void *desired_addr, size_t length, int memory_protections, int mapping_flags, int fd, off_t offset_within_file); /* mapping_flags values MAP_SHARED Create a mapping shared by all shared mappers MAP_PRIVATE Create a private (copy-on-write) mapping MAP_FIXED Map at desired_addr, or else fail */ /* memory_protections PROT_READ Read permission for the memory area PROT_WRITE Write permission for the memory area PROT_EXEC Execute permission for the memory area PROT_NONE No permissions for the memory area */ //mmap returns the address at which the mapping was performed, or MAP_FAILED if the call failed. msync — Make a mapping consistent with the underlying object.. int msync(const void *addr, size_t length, int flags); /* flags MS_SYNC Synch the data out now and don't return until it's done. MS_ASYNC Start the synch operation and immediately return. MS_INVALIDATE Invalidate cached copies of the data that are inconsistent with the synched data. useful for multiprocessed or multiple mapping. */ munmap — Undo a mapping established by mmap. int munmap(void *addr, size_t length);

Memory locking
.
Memory locks are not inherited by children created by fork, and are also abandoned when exit or one of the exec functions are called. locks a process address space into physical memory, rendering the memory immune from being paged or swapped to disk. #ifdef _POSIX_MEMLOCK_RANGE mlock—Lock a range of memory. don't use more then 3 times for stacking. int mlock(const void *addr, sizet len); mlockall—Lock your entire memory space down. don't use more then 10 times for stacking. int mlockall(int how); /* flag how : MCL_CURRENT and MCL_FUTURE. */ munlock—Unlock a range of memory. int munlock(const void *address, size_t length); munlockall—Unlock your entire address space. int munlockall (); After a call to munlockall, a process's memory may be paged or swapped.

Page Size and Allingment
always take care page size when you pass size to memroy calls. Example code. long psize = sysconf(_SC_PAGE_SIZE); long offset = (long)addr%psize; long align_addr = (long)addr - offset; long sync_size = 0; sync_size = (long)addr + size - align_addr; long page_num = sync_size / psize; if( (sync_size % psize) > 0 ){ page_num++; } sync_size = psize * page_num; msync( (void*)align_addr, sync_size, MS_SYNC | MS_INVALIDATE ); syconf #include sysconf — Query system options at run-time. long sysconf(int option); long psize = sysconf(_SC_PAGE_SIZE); // get system page size

Persistents in POSIX
Shared memory is persistent so long as the system remains up. you can create and map a shared memory region, store some data into it, close and unmap it, go away for a few days, then come back and still see the data you stored, assuming no one unlinks the shared memory object in the meantime. Application should always include a startup phase where the status and general sanity of all required objects, including shared memory, is assured. Such a phase might consist of just shm_unlinking all needed shared memory objects before anyone opens them up—just to be sure that the memory, when created and mapped, is empty. This concept should used with all kind of POIX objects.


Posix Semaphoe in Linux

Posix Semaphoe in Linux

macro defined
_POSIX_SEMAPHORES
Header file
#include <semaphore.h>

Types of semaphore in Posix
1.
unnamed semaphore
use in related process, parnet-chiled, multithreaded process. 2.
named semaphore
can use in unrelated process and related process.

APIs for semaphores in Posix

unnamed semaphore
sem_init — Initialize a POSIX unnamed semaphore.
int sem_init(sem_t *sem_location, int pshared,unsigned int value);
/* sem_location: memory address where semaphore initlized, phsared : is this shared by multiple process 0=no sharing, 1=sharing. value : initial value of semaphore but never negative.number of process can lock this semaphore. */ sem_destroy — Deinitialize a POSIX unnamed semaphore.
int sem_destroy(sem_t *sem_location);

named semaphore
sem_open — Create/access a POSIX named semaphore.
sem_t * sem_open(char *sem_name, int oflags,mode_t mode, unsigned int value);
sem_close—Terminate access to a POSIX named semaphore. // close opend semaphore instance.
int sem_close(sem_t *sem);
sem_unlink—Destroy a POSIX named semaphore. // remove semaphore, only opned semaphore will continue work untill they closed.
int sem_unlink(char *semname);

Operation on semaphore
sem_getvalue—Get the value of a POSIX semaphore (named or unnamed). // get semaphore value // if positive unblocked, zero blocked.
int sem_getvalue(sem_t *sem, int *value);
sem_wait, sem_trywait—Wait on a POSIX semaphore (named or unnamed). // lock semaphore.
int sem_wait(sem_t *sem);
// blocking
int sem_trywait(sem_t *sem);
// non blocking sem_post—Post (signal) a POSIX semaphore (named or unnamed). // unlock semaphore.
int sem_post(sem_t *sem);

Difference Between Semaphores and Mutex
noticeable differences between semaphore and Mutex. 1. A semaphore can be a Mutex but a Mutex can never be semaphore. This simply means that a binary semaphore can be used as Mutex, but a Mutex can never exhibit the functionality of semaphore. 2. Both semaphores and Mutex (at least the on latest kernel) are non-recursive in nature. 3. No one owns semaphores, whereas Mutex are owned and the owner is held responsible for them. This is an important distinction from a debugging perspective. 4. In case the of Mutex, the thread that owns the Mutex is responsible for freeing it. However, in the case of semaphores, this condition is not required. Any other thread can signal to free the semaphore by using the sem_post() function. 5. A Mutex, by definition, is used to serialize access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A semaphore, by definition, restricts the number of simultaneous users of a shared resource up to a maximum number 6. Another difference that would matter to developers is that semaphores are system-wide and remain in the form of files on the filesystem, unless otherwise cleaned up. Mutex are process-wide and get cleaned up automatically when a process exits. 7. The nature of semaphores makes it possible to use them in synchronizing related and unrelated process, as well as between threads. Mutex can be used only in synchronizing between threads and at most between related processes (the pthread implementation of the latest kernel comes with a feature that allows Mutex to be used between related process). 8. According to the kernel documentation, Mutex are lighter when compared to semaphores. What this means is that a program with semaphore usage has a higher memory footprint when compared to a program having Mutex. 9. From a usage perspective, Mutex has simpler semantics when compared to semaphores.
referenced : linuxdevcenter.com


Exception in C++

Exception in C++
how to write code for exception handling in C++, what need to be take care, sorry i am not writing each every kind of code, just only some points.
Exception do and don't uses
try{ .... .... throw ex; throw (new GFException()); } catch(rutime_exception& ex) // always use by referance. { ......... throw; // rethorow excpetion, no change in type of original exception } catch(excpetion ex) // bad, twice copy, object slicing. { ......... throw ex; // rethrow, but static type changed , if handling dynamic type exception } catch(GFException* exGF) // bad who will take ownership of exGF { ................. }
exception specifications
void f1(); // might throw any exception. void f1() thorw(int); // only throw int exception void f1() thorw(); // it's not throw any exception.


Exception do and don't uses
1. use smart pointer to utilze destructor call and prevent resource leak when excpetion occured. 2. handle exception in constructor. 1. constructor use try{......}catch(...){cleanup; throw;} 2. use smart pointer this is best solution. 3.prevent throwing exception from destructor exception. if destructor called by stack unwinding, mean one exception allready active and now if destructor throw exception, C++ calls terminates. terminate function : it terminates execution of your program. Furthermore, it terminates it immediately; not even local objects are destroyed 4. regardless of whether the exception is caught by value or by reference, throw make a copy of thrown object and passed to catch clause.C++ specifies that an object thrown as an exception is copied.Copying is always based on an object’s static type. 5. throw; this statment rethrow the current exception, it's not change the type of the exception being propagated. efficient, not generate a new exception object. 6. catch(MyException ex){ throw ex;} this change type of original exception when propagating. original exception can derived type of exception from MyException. 7. never throw a pointer to a local object, because local object destroyed before catch use object. 8. catch can do 2 kind of conversion for parameters. 1. derived to base. 2. typed to an untyped pointer. catch(const void*) can handle any pointer type. 9. catch are "first fit" but virutal function are "best fit" algorithems. never put a base class catch clause before derived class catch clause. 10. never return or throw local object as pointer. return object destroyed before used by pointer. Pointer aha, who will take ownership for deleting from heap. 11. catch expection by value problems, twice copy and object slicing. 12. best option of catch exception use by referance[no copy, no object slicing, no ownership], just remember this no value, no pointer in catch only referance. 13. if a function throws an exception not listed in its exception specification, this call runtime special function unexpected. unexpected->termincate->abort. what your program aborted!!!!! 14. Templates don't use exception specifications. we don't know what will be type of template, is that type follow our exception specifications.



---------This is Draft Version, still learning----------------



Constructor and destructor design in C++


constructor called done in 2 steps. 1. member initialization.
// this call constructor
2. call of constructor body.
// this call assignment operator
MyClass():member(),base(){
step1
x=val;
step2
}


1. use initialization list for members. if list long use init method. 2. define default constructor otherwise unable create array of object. 3. define virtual destructor if need to use base* to reference to derived object. 4. always define empty implementation for virtual destructor.virtual destructor work is that the most derived class's destructor is called first, then the destructor of each base class is called. 5. order of member initialization in order they declare in class. 6. virtual function increase object size by vptr, if your class doesn't need any virtual function then try to avoid virtual destructor. 7. ownership of pointer data members need to take care for all kind of constructor and assignment operator and destructor. 8. avoid object creation by default constructors.It's looks like using variable without initializing or 2 step initialization overhead, better to use constructor which take initialization input data. create a object using default constructor. assign or initialized data.


copy constructor
derived copy constructor should call base copy constrictor. do assignment for all data members. ownership of pointer data need to take care similar to constructor.

-----------STILL DRAFTING---------

Pointer and Reference in C++



Prefer pass-by-reference to pass-by-value.

  • pass-by-value increase overhead of calling copy constructor [derived> base2> base1] and destructor, this lead to reduced performance.
  • pass-by-reference remove object-slicing problem by bitwise copying.

class Person{ string firstname, lastname; }; string getFullName(Person person) { return (person.firstname+person.lastname); }
Person blogger("Viru","Rathore"); cout<<blogger.getFullName();
Person class copy constructor call 2 copy constructor for string members. string copy constructor for return by value. // very carefully select when return by reference or value destructor for both string members. destructor for person class.
Do and Don't pointer and reference uses in C++.
  1. pointer and reference should should not refer to temp objects.
    1. const char* data = Person.getName().c_str(); // return temp string object
    2. cout<<data; // temp destroyed and result will be undefined.
  2. Avoid member functions that return non-const pointers or references to members less accessible than themselves. public function should not return private or protected data member by reference or pointer.
  3. Function that returns a dereferenced pointer is a memory leak.
  4. Don't return a reference to a local object.


use default parameter or overloading:

  • default parameter : if need a single algorithm and some default value can be possible.
  • overloading : if algorithm depends on input and there is not possible default values.
  • Avoid overloading on a pointer and a numerical type.
  • void testfun(int); void testfun(stirng*); testfun(0); // always calls testfun(int)
  • Guard against potential ambiguity.


Assignment Operator in C++

Step for assignment operator
  1. check for self assignment
  2. call base assignment operator. // this should take care for copy constructor.
  3. remove existing allocated memory for members
  4. assign memory for members
  5. do assignment for all data members.
  6. return *this.

Derived& Derived::operator=(const Derived& rhs) { if (this == &rhs) return *this;
// equality based on address or value identity.
static_cast<Base&>(*this) = rhs;
// call this->Base::operator=
y = rhs.y; return *this; }

--------------still in draft-------------------