Saturday, July 28, 2012

My experience on C++ Serialization Solutions

Recently I tried 3 solutions for serializing request data in my Apache filter module in C++:
1- Google Protocol Buffer
2- boost serialization
3- msgpack
I was disappointed of using solutions 1 and 2 because of errors I faced. I submitted errors in many forums and related mailing lists, but I couldn't get any answer.
Google protocol buffer seems professional but It needs classes to be defined in specific way which that protocol forces.
BTW I started with this solution and designed *.protoc files and generated my model files.
the solutions worked fine in a console application but I've got segmentation fault in Apache module without any specific error. ( I tried debugging with gdb, ddd,.... but no chance to resolve the error).
So I switched to boost serialization. It was much simpler than Google solution but It didn't work completely.
It worked fine in console application and Apache filter too.
but I've segfault when I tried to serialize nested classes.
I returned to my mind, searching a solution recommended by one of my friends( Kamyar, which has been used that solution in .NET).
It was msgpack, the 3rd solution.
It's much simple than Google solution and even simpler than boost serialization.
It worked fine without any headache. As msgpack website says, It's much fast from Google and boost solution :
http://www.msgpack.org

Friday, July 27, 2012

How to run class member function in C++11 thread


class X
{
private:
 int mX;
public:
 F()
 {
   // some work
 }
};

void thread_sample()
{
  X x;
  std::thread th(&X::F,&x);
  th.join(); // call detach() if you want this method not to wait for F() to finish
 }

Tuesday, July 17, 2012

Simplest threading sample in C++11

If you were looking for multitasking and threading library in C++.
C++11 standard brought multitasking for you in the best way.
Here is the simplest threading sample in C++11. I'll post more advanced samples progressively.
I've tested this code sample in VS2012 RC(It's free for download).
#include <thread>
#include <iostream>
void hello()
{
 std::cout << "hello multitasking world!";
}
int main(int argc, char* argv[])
{
 std::thread tr(hello);
 tr.join();
 getchar();
 return 0;
}




"Execute Around Sequence", C++ Pattern

For clearing the need for this pattern, I start this post with a problem statement.
Problem:
"suppose that we have a pair of actions that surrounds a sequence of  statements and we need abstract that actions around the statements and have a error prone and exception safe code".
Let's start with a sample code snippet :
void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
  
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

  |---------------------------------------------------------------------------------------------------------|
   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|


}
    ---------------- Code 1 -----------------------
What happens in "Code 1" if an exception occur in block 2?. Answer is easy; block 3 won't run! So acquired lock will not be unlocked and other threads will waiting for unlock forever, allocated memory in part 1 won't be freed and all resources acquired in part1 won't be released.
Solution:
Initial solution which may bloom in your mind may be following strategy :

void F()
{
  |----------------------------------------------------------------------------------------------------------|

  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try

{
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|
} catch(...)
{
  throw ;
}
finally
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}
}

    ---------------- Code 2-----------------------
But as you know, C++ doesn't have finally statement in exception handling. So we have to change the code as following :


void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try
{

  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

} catch(...)
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

  throw ;
}

  |---------------------------------------------------------------------------------------------------------|
   |3'. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}

    ---------------- Code 3-----------------------
Code 3 is an acceptable solution but how about the case you are not allowed to use try/catch ?
Considering this fact that destructor of C++ class will run automatically if object goes out of scope, guides us to write a class and put "block 1" of Code 1 into a constructor of class and "block 3" of Code 1 into destructor of that class. This way helps us to achieve an exception safe code which is named executive around sequence :

class scoped_resource_manager
{
public:
  scoped_resource_manager(resource_related_parameters)
{
     block 1 : acquires lock,allocate memory, open connections ....
}
~scoped_resource_manager()
{
     block 3 :  release lock, free memory , close  connection ...
}

}

void F()
{
 scoped_resource_manager resource_manager(resource_related_parameters);
  |----------------------------------------------------------------------------------------------------|

  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

}

    ---------------- Code 4-----------------------
In Code 4, we are not worry if exception occurs in block 2 or not; all allocated resources will be released  when function returns or execution steps out of it's scope because of automatically running  of scoped_resource_manager class destructor.!

Thanks for C++ class destructors.
"Finally" here is a simple real world code sample for you :
 class ScopedConnection
{
 private :
  BaseDBProvider *mDB;
 public:
  ScopedConnection(BaseDBProvider *pDB)
  {
   mDB=pDB;
   mDB->Open();
                       mDB->StartTransaction();
                }
  ~ScopedConnection()
  {
                        mDB->DetachTransaction();
                  mDB->Close();
  }
};
void F()
{
 BaseDBProvider *bdp=DBFactory::GetDBProvider();
 ScopedConnection scoped_con(bdp);
 DBDataReader *dr;
 dr=bdp->ExcecuteReader(dbs);
 while(dr->ReadNext())
  ret->push_back(Load(dr));
 return ret;
}

scoped_ptr<T> and scoped_lock ( from boost library ) are also implemented to help us in such problems.

Sunday, July 1, 2012

Decompose text to valid words (Word breaking)

Given a dictionary of valid words and an input text, write a function to check if the input text can be decomposed into valid words from dictionary.
Hint 1: use dynamic programming technique.
Hint 2: define T[k] is true if text[0...k] can be decomposed into valid words
Hint 3: T[k] is true if there exists any j : 0..k-1 where T[j] is true and text[j..k] is a valid word in dictionary.
This hints help us to write a simple loop to get the answer.


static string dic[4]={"bed","bath","beyond","and"};

bool decomps(string txt)
{
 map<string,bool> dm;
 for(int i=0;i<4;i++)
  dm[dic[i]]=true;
 vector<bool> t(txt.size()+1,false);
 t[0]=true;
 for(int k=1;k<=txt.size();k++)
 {
  bool candecomp=false;
  for(int i=0;i<k;i++)
  {
   string srch=txt.substr(i,k-i);
   map<string,bool>::iterator f=dm.find(srch);
   if(t[i]==true && f!=dm.end())
   {
    t[k]=true;
    break;
   }
  }
 }
 return t[txt.size()];
}
void  test_decomp()
{
 cout << decomps("bedbathandbeyond");
}

Saturday, July 28, 2012

My experience on C++ Serialization Solutions

Recently I tried 3 solutions for serializing request data in my Apache filter module in C++:
1- Google Protocol Buffer
2- boost serialization
3- msgpack
I was disappointed of using solutions 1 and 2 because of errors I faced. I submitted errors in many forums and related mailing lists, but I couldn't get any answer.
Google protocol buffer seems professional but It needs classes to be defined in specific way which that protocol forces.
BTW I started with this solution and designed *.protoc files and generated my model files.
the solutions worked fine in a console application but I've got segmentation fault in Apache module without any specific error. ( I tried debugging with gdb, ddd,.... but no chance to resolve the error).
So I switched to boost serialization. It was much simpler than Google solution but It didn't work completely.
It worked fine in console application and Apache filter too.
but I've segfault when I tried to serialize nested classes.
I returned to my mind, searching a solution recommended by one of my friends( Kamyar, which has been used that solution in .NET).
It was msgpack, the 3rd solution.
It's much simple than Google solution and even simpler than boost serialization.
It worked fine without any headache. As msgpack website says, It's much fast from Google and boost solution :
http://www.msgpack.org

Friday, July 27, 2012

How to run class member function in C++11 thread


class X
{
private:
 int mX;
public:
 F()
 {
   // some work
 }
};

void thread_sample()
{
  X x;
  std::thread th(&X::F,&x);
  th.join(); // call detach() if you want this method not to wait for F() to finish
 }

Tuesday, July 17, 2012

Simplest threading sample in C++11

If you were looking for multitasking and threading library in C++.
C++11 standard brought multitasking for you in the best way.
Here is the simplest threading sample in C++11. I'll post more advanced samples progressively.
I've tested this code sample in VS2012 RC(It's free for download).
#include <thread>
#include <iostream>
void hello()
{
 std::cout << "hello multitasking world!";
}
int main(int argc, char* argv[])
{
 std::thread tr(hello);
 tr.join();
 getchar();
 return 0;
}




"Execute Around Sequence", C++ Pattern

For clearing the need for this pattern, I start this post with a problem statement.
Problem:
"suppose that we have a pair of actions that surrounds a sequence of  statements and we need abstract that actions around the statements and have a error prone and exception safe code".
Let's start with a sample code snippet :
void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
  
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

  |---------------------------------------------------------------------------------------------------------|
   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|


}
    ---------------- Code 1 -----------------------
What happens in "Code 1" if an exception occur in block 2?. Answer is easy; block 3 won't run! So acquired lock will not be unlocked and other threads will waiting for unlock forever, allocated memory in part 1 won't be freed and all resources acquired in part1 won't be released.
Solution:
Initial solution which may bloom in your mind may be following strategy :

void F()
{
  |----------------------------------------------------------------------------------------------------------|

  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try

{
  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|
} catch(...)
{
  throw ;
}
finally
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}
}

    ---------------- Code 2-----------------------
But as you know, C++ doesn't have finally statement in exception handling. So we have to change the code as following :


void F()
{
  |----------------------------------------------------------------------------------------------------------|
  |1. block of code which acquires lock, memory or other resources and some other statements |
  |----------------------------------------------------------------------------------------------------------|
   try
{

  |----------------------------------------------------------------------------------------------------|
  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

} catch(...)
{
  |---------------------------------------------------------------------------------------------------------|

   |3. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

  throw ;
}

  |---------------------------------------------------------------------------------------------------------|
   |3'. block of code which release lock, memory or other resources and some other statements |
  |---------------------------------------------------------------------------------------------------------|

}

    ---------------- Code 3-----------------------
Code 3 is an acceptable solution but how about the case you are not allowed to use try/catch ?
Considering this fact that destructor of C++ class will run automatically if object goes out of scope, guides us to write a class and put "block 1" of Code 1 into a constructor of class and "block 3" of Code 1 into destructor of that class. This way helps us to achieve an exception safe code which is named executive around sequence :

class scoped_resource_manager
{
public:
  scoped_resource_manager(resource_related_parameters)
{
     block 1 : acquires lock,allocate memory, open connections ....
}
~scoped_resource_manager()
{
     block 3 :  release lock, free memory , close  connection ...
}

}

void F()
{
 scoped_resource_manager resource_manager(resource_related_parameters);
  |----------------------------------------------------------------------------------------------------|

  |--2. ---- Sequences of statements                                                     |
  |----------------------------------------------------------------------------------------------------|

}

    ---------------- Code 4-----------------------
In Code 4, we are not worry if exception occurs in block 2 or not; all allocated resources will be released  when function returns or execution steps out of it's scope because of automatically running  of scoped_resource_manager class destructor.!

Thanks for C++ class destructors.
"Finally" here is a simple real world code sample for you :
 class ScopedConnection
{
 private :
  BaseDBProvider *mDB;
 public:
  ScopedConnection(BaseDBProvider *pDB)
  {
   mDB=pDB;
   mDB->Open();
                       mDB->StartTransaction();
                }
  ~ScopedConnection()
  {
                        mDB->DetachTransaction();
                  mDB->Close();
  }
};
void F()
{
 BaseDBProvider *bdp=DBFactory::GetDBProvider();
 ScopedConnection scoped_con(bdp);
 DBDataReader *dr;
 dr=bdp->ExcecuteReader(dbs);
 while(dr->ReadNext())
  ret->push_back(Load(dr));
 return ret;
}

scoped_ptr<T> and scoped_lock ( from boost library ) are also implemented to help us in such problems.

Sunday, July 1, 2012

Decompose text to valid words (Word breaking)

Given a dictionary of valid words and an input text, write a function to check if the input text can be decomposed into valid words from dictionary.
Hint 1: use dynamic programming technique.
Hint 2: define T[k] is true if text[0...k] can be decomposed into valid words
Hint 3: T[k] is true if there exists any j : 0..k-1 where T[j] is true and text[j..k] is a valid word in dictionary.
This hints help us to write a simple loop to get the answer.


static string dic[4]={"bed","bath","beyond","and"};

bool decomps(string txt)
{
 map<string,bool> dm;
 for(int i=0;i<4;i++)
  dm[dic[i]]=true;
 vector<bool> t(txt.size()+1,false);
 t[0]=true;
 for(int k=1;k<=txt.size();k++)
 {
  bool candecomp=false;
  for(int i=0;i<k;i++)
  {
   string srch=txt.substr(i,k-i);
   map<string,bool>::iterator f=dm.find(srch);
   if(t[i]==true && f!=dm.end())
   {
    t[k]=true;
    break;
   }
  }
 }
 return t[txt.size()];
}
void  test_decomp()
{
 cout << decomps("bedbathandbeyond");
}