Category Archives: C++ 11

psa.exe partial tree sample

Process Status Analysis – the first steps

I am pleased to announce my first cross-platform and open source project, the Process Status Analysis tool, available on GitHub.

The Process Status Analysis (psa) version 0.2 is available for Windows and Linux (Debian derived / Ubuntu tested) Operating Systems.
Download: psa for Ubuntu Linux x64 (4906 downloads)
Download: psa for Ubuntu Linux x86 (4152 downloads)
Download: psa.exe for Windows x64 (4115 downloads)
Download: psa.exe for Win32 (4083 downloads)

You may wonder why I did it or what it brings new. Well, I did it for fun, in my spare time and I will continue improving it when I’ll find a time to do it.

The project is written in modern C++ using idioms from the C++ 1x standards. Even if initially was done as a C++ for Windows only, during the past days I managed the port of it for Linux using Visual Studio 2017’s project templates and a connection via SSH.
In general, the source code base is similar, differing just by OS specific stuff.

In case you want to find out more about how to develop C++ Linux projects from the best development tool (imho), Visual Studio, you can find more information on Visual Studio development team blog.

Related to this psa project, the Linux version requires libprocps4-dev library in order to build.

The main reason for starting this project was that I wanted to know what’s the total memory amount used by my Chrome browser. I know it uses a lot of resources, but not that much… 🙂

Even if my preferred processes analysis tool, the Process Hacker offers a lot of processes administration possibilities, but it didn’t provide what I want, so I decided to enjoy a bit.

Chrome processes in Process Hacker

Sample – Google Chrome processes in Process Hacker tool

So, what I achieved by psa.exe was something like:

C:\Windows\system32> psa -o chrome
PID [896] chrome.exe 237.5234 MB
PID [1496] chrome.exe 87.6875 MB
PID [2388] chrome.exe 166.5000 MB
PID [5860] chrome.exe 3.1211 MB
PID [7336] chrome.exe 273.2188 MB
PID [8444] chrome.exe 68.0508 MB
PID [8624] chrome.exe 63.3945 MB
PID [9180] chrome.exe 296.9766 MB
PID [10600] chrome.exe 292.6289 MB
PID [12352] chrome.exe 182.5977 MB
PID [13688] chrome.exe 2.3555 MB
PID [14052] chrome.exe 73.1875 MB
PID [16200] chrome.exe 211.9805 MB
PID [17284] chrome.exe 55.7148 MB
PID [18036] chrome.exe 208.6680 MB
PID [19012] chrome.exe 457.2305 MB
PID [19312] chrome.exe 143.4766 MB
-----------------------------------
Total used memory: 2824.31 MB

A bit too much in my humble opinion…
The features this tool offers includes:

Get all processes loaded in memory information

I case you want to have a snapshot of all the processes loaded in the OS’s memory you can have it with.

psa -a

Get process only used memory

With psa.exe you can reach the used memory by a specific parameter -o after the process name or at least a part of its name.

psa -o chrome             // find how much memory uses your Chrome!   o_O

Currently, there is no string replace ‘*’ but it’s ongoing.


Print processes tree

Storing the processes’ data within a generic tree done by me, I took the decision to print the processes’ tree output, similarly there is in Windows with tree.exe tool or on Linux in pstree or even htop.

./psa -t
./psa -t 1034

psa.exe partial tree sample

Process Status Analysis partial tree of Windows process

Top most “expensive” processes

In case you want to see what are the most expensive processes within your operating system, you can achieve it with:

psa -e 20

or simpler psa -e in case you’re sure you want top 10 expensive processes (the default value).

silviu@ubuntu-dev-server:~/projects/psa-lin/bin/x64/Release$ ./psa -e
Top 10 consuming memory processes
-------------------------------------------
PID        Process Name         RAM Usage
-------------------------------------------
[924]    /usr/lib/policykit-1/polkitd   270.68 MB
[906]    /usr/lib/accountsservice/accounts-daemon       269.43 MB
[842]    /usr/sbin/rsyslogd     250.39 MB
[878]    /usr/lib/snapd/snapd   197.29 MB
[531]    /lib/systemd/systemd-timesyncd         97.97 MB
[1614]    sshd: silviu@pts/0    93.16 MB
[1576]    sshd: silviu [priv]   93.16 MB
[863]    /usr/bin/lxcfs         93.13 MB
[427]    /sbin/lvmetad          92.55 MB
[1034]    /usr/sbin/sshd        63.98 MB
-------------------------------------------


C:\Windows\system32> psa -e 10
Top 10 consuming memory processes
-------------------------------------------
PID        Process Name         RAM Usage
-------------------------------------------
[19012]    chrome.exe           435.67 MB
[17684]    chrome.exe           329.51 MB
[7336]    chrome.exe            259.61 MB
[15576]    devenv.exe           248.20 MB
[896]    chrome.exe             222.85 MB
[2388]    chrome.exe            188.21 MB
[18428]    chrome.exe           184.48 MB
[15760]    chrome.exe           173.82 MB
[488]    Dropbox.exe            162.15 MB
[5488]    googledrivesync.exe   161.11 MB
-------------------------------------------
Total used memory: 2365.61 MB

Redirect output to a file

From the standard output the information can be easily redirected to a file.

c:\> psa -t > windows_processes_tree.txt
# ./psa -t > linux_processes_tree.txt        

Kill process feature

This feature was not implemented yet but in case we need it we can be done it easily with the existing tools on the target OS (ex. Task Manager, Process Exporer/Hacker, pskill.exe for Windows or the combination ps + kill on LInux).

Feedbacks and improvements
Any constructive feedback, suggestions, contributions to improvements are appreciated.
Feel free to add any issue you find, wish or suggestion you have in the GitHub repository, the 
Issues section or here as a comment.

The First Hackathon Experience #HackTM2016

It has passed approximately two months from my first hackathon experience, the #HackTM2016 from Timisoara. This delay I’m publishing this article is mostly because of the release period to the job and other personal stuff I had to do.

This experience was a reminder of my high school programming competitions where I have attended with different applications written in the already ancient Turbo Pascal 7.0 or Borland C++ 3.1. At that moment, probably because of my high school informatics great teachers, the competitive spirit between colleagues was so intense and we have competed for each other in creating applications within the local competitions and in other cities from the country.

This year, the hackathon competition from Timisoara was between 20 – 22 May 2016 to the UPT Restaurant, Timisoara and from my point of view it was a great event. The event had categories such eHEALTH, Robots, Smart City, GameDev, IoT, Education, Fintech and Open but no Automotive category as I expected according to previous pitching sessions.

Before the effective event, I have attended in two pitching sessions seeing different challenging proposals in few domains. The most appealing were some ideas of the ADAS team from Continental, a team I was apart between 2006-2008 (Siemens VDO department, video camera projects at that time).

Even if I had no team, because of curiosity, I bought the ticket and I went to the hackathon pitching session, trying to figure a team and to decide a project to deal with.

The Continental ADAS team came with hardware and software support how to hack their platform.

We were able to find a small team, first by two persons and later for a period five persons. Unfortunately, those last three persons left us while realizing that the project is not what they have imagined initially, that other projects look more challenging or that their knowledge was not matching with what it was required for our project.
So, I installed on my laptop some software used internally by the ADAS team and we took a ride to record real traffic data. Once we had this data, the effective programming for grabbing it can be done in office conditions.

Driving to grab ADAS data

The idea

Having the radar and camera information, GPS data and vehicle dynamics, we were thinking is that in the near future, even before self-driving cars on the common roads, this information might be sent in the cloud to be used by the traffic management solutions in order to be optimized the traffic. Even these days, in my city, Timisoara, such traffic management solution is implemented but is not based on cars internal information. Maybe, this idea will not be applied.

What we have done – the effective experience

So, faced with this challenge, me and my teammate Nikola Kolevski, a Serbian nice guy, have started the work on Friday evening. We have met on that pitching meeting and we had a great cooperation. I was the back-end guy and he the man from the cloud. Because we “spoke” different languages, me C++ and he Python, we have decided to speak the REST way.

During our job, we have improvised the “project management” with a Trello board. Of course, we used GitHub for source control.

What I effectively had to do it was to inject some code within a .DLL that was loaded into a Continental application and sent the ADAS information in the cloud. Nicola was the guy that received and collected the data. Unfortunately, even if we tried few times, we found no front-end available teammate, just some with slices of time in terms of availability.

ADAS AE-RO HackTM concept

I decided to use the benefits of asynchronous programming and I used the Casablanca REST API. But because of the Continental’s Visual Studio 2012 project constraints (!!!), during the Friday evening, I faced up with the challenge to find and adapt a Casablanca library older version to the project. The latest Casablanca’s versions are available for VS 2013 and VS 2015 only. Thanks to NuGet tool, I finally managed to get and use the 1.10 version.

On Saturday we managed the effective work, faced with some challenges related to the TCP/IP communication between our applications because of some Python server configuration, but finally, our applications were able to talk each other via REST services, in the night and I have tweeted.

After a sleep break, next morning we did some last code adjustments and being time constrained we tried to improvise a frontend. Also, we had a second trip with the Continental’s Mercedes car to test what we did, using a 4G network.

As usual for a hackathon, everything was on the run with adrenaline, so quite nice! At the end of the hackathon, we had to prepare for the hackathon jury’s visit and later for presentation because we have qualified in the first three teams in the Robots section. Yeah, we were included there because the Automotive category did not exist, but it was fine. 🙂

The truth is that the Continental was the only automotive represented company even if there are many such companies in Timisoara, but it seems they are not interested in such events.

Other interesting things from #HackTM2016

Attending to #HackTM2016 was a great experience, I have seen many interesting projects but from far the most exciting one was the Symme 3D Printer, a local start-up.

Conclusions

In an internet of things world, our based idea might connect the cars ADAS information with intelligent management future systems to improve the traffic flow in big cities.

It is obvious but I want to underline: if you want to have success in a hackathon, try having a core team before the event. Otherwise, you might just have fun coding but not ending the prototype.  Strategies of being efficient would be a great asset.

Meeting new people and trying to do something from the scratch in a limited time is a very cool thing even if you don’t have time to write optimized and tested code. Also, you might learn a lot of new things.

Definitely, I will repeat this experience in the future!

GitHub Project Repository
https://github.com/HackTM2016/SpeedFeed

Several C++ singleton implementations

This article offers some insight into singleton design-pattern.
The singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. The GoF book describes the singleton as: “Ensure a class only has one instance, and provide a global point of access to it.
The Singleton design pattern is not as simple as it appears at a first look and this is proven by the abundance of Singleton discussions and implementations. That’s way I’m trying to figure a few implementations, some base on C++ 11 features (smart pointers and locking primitives as mutexs). I am starting from, maybe, the most basic singleton implementation trying to figure different weaknesses and tried to add gradually better implementations.
The basic idea of a singleton class implies using a static private instance, a private constructor and an interface method that returns the static instance.

Version 1
Maybe, the most common and simpler approach looks like this:

class simpleSingleton {
  simpleSingleton();
  static simpleSingleton* _pInstance;

public:
  ~simpleSingleton() {}
  static simpleSingleton* getInstance() {
    if (!_pInstance) {
      _pInstance = new simpleSingleton();
    }
    return _pInstance;
  }
  void demo() {
    std::cout << "simple singleton # next - your code ..." << std::endl;
  }
};

simpleSingleton* simpleSingleton::_pInstance = nullptr;

Unfortunately this approach has many issues. Even if the default constructor is private, because the copy constructor and the assignment operator are not defined as private the compiler generates them and the next calls are valid:

// Version 1
simpleSingleton * p = simpleSingleton::getInstance(); // cache instance pointer p->demo();

// Version 2
simpleSingleton::getInstance()->demo();

simpleSingleton ob2(*p); // copy constructor
ob2.demo();

simpleSingleton ob3 = ob2; // copy constructor
ob2.demo();

So we have to define the copy constructor and the assignment operator having private visibility.

Version 2 – Scott Meyers version
Scott Meyers in his Effective C++ book adds a slightly improved version and in the getInstance() method returns a reference instead of a pointer. So the pointer final deleting problem disappears.
One advantage of this solution is that the function-static object is initialized when the control flow is first passing its definition.

class otherSingleton {
  static otherSingleton* pInstance;

  otherSingleton();

  otherSingleton(const otherSingleton& rs) { pInstance = rs.pInstance; }

  otherSingleton& operator=(const otherSingleton& rs) {
    if (this != &rs) {
      pInstance = rs.pInstance;
    }

    return *this;
  }

  ~otherSingleton();

 public:
  static otherSingleton& getInstance() {
    static otherSingleton theInstance;
    pInstance = &theInstance;

    return *pInstance;
  }

  void demo() {
    std::cout << "other singleton # next - your code ..." << std::endl;
  }
};

otherSingleton * otherSingleton::pInstance = nullptr;

The destructor is private in order to prevent clients that hold a pointer to the Singleton object from deleting it accidentally. So, this time a copy object creation is not allowed:

otherSingleton ob = *p;
ob.demo();


error C2248: otherSingleton::otherSingleton ' : cannot access private member declared in class 'otherSingleton'
error C2248: 'otherSingleton::~otherSingleton' : cannot access private member declared in class 'otherSingleton'

but we can still use:

// Version 1
otherSingleton *p = &otherSingleton::getInstance(); // cache instance pointer p->demo();
// Version 2
otherSingleton::getInstance().demo();

This singleton implementation was not thread-safe until the C++ 11 standard. In C++11 the thread-safety initialization and destruction is enforced in the standard.

If you’re sure that your compiler is 100% C++11 compliant then this approach is thread-safe. If you’re not such sure, please use the approach version 4.

Multi-threaded environment
Both implementations are fine in a single-threaded application but in the multi-threaded world things are not as simple as they look. Raymond Chen explains here why C++ statics are not thread safe by default and this behavior is required by the C++ 99 standard.
The shared global resource and normally it is open for race conditions and threading issues. So, the singleton object is not immune to this issue.
Let’s imagine the next situation in a multithreaded application:

static simpleSingleton* getInstance() {
  if (!pInstance)  // 1
  {
    pInstance = new simpleSingleton();  // 2
  }

  return pInstance;  // 3
}

At the very first access a thread call getInstance() and pInstance is null. The thread reaches the second line (2) and is ready to invoke the new operator. It might just happen that the OS scheduler unwittingly interrupts the first thread at this point and passes control to the other thread.
That thread follows the same steps: calls the new operator, assigns pInstance in place, and gets away with it.
After that the first thread resumes, it continues the execution of line 2, so it reassigns pInstance and gets away with it, too.
So now we have two singleton objects instead of one, and one of them will leak for sure. Each thread holds a distinct instance.

An improvement to this situation might be a thread locking mechanism and we have it in the new C++ standard C++ 11. So we don’t need using POSIX or OS threading stuff and now locking getInstance() from Meyers’s implementation looks like:

static otherSingleton& getInstance() {
  std::lock_guard lock(_mutex);
  static otherSingleton theInstance;
  pInstance = &theInstance;
  return *pInstance;
}

The constructor of class std::lock_guard (C++11) locks the mutex, and its destructor unlocks the mutex. While _mutex is locked, other threads that try to lock the same mutex are blocked.
But in this implementation we’re paying for synchronization overhead for each getInstance() call and this is not what we need. Each access of the singleton requires the acquisition of a lock, but in reality we need a lock only when initializing pInstance. If pInstance is called n times during the course of a program run, we need the lock only for the first time.
Writing a C++ singleton 100% thread safe implementation it’s not as simple as it appears as long as for many years C++ had no threading standard support. In order to implement a thread-safe singleton we have to apply the double-checked locking (DCLP) pattern.
The pattern consists of checking before entering the synchronized code, and then check the condition again.
So the first singleton implementation would be rewritten using a temporary object:

static simpleSingleton* getInstance() {
  if (!pInstance) {
    std::lock_guard lock(_mutex);

    if (!pInstance) {
      simpleSingleton* temp = new simpleSingleton;
      pInstance = temp;
    }
  }

  return pInstance;
}

This pattern involves testing pInstance for nullness before trying to acquire a lock and only if the test succeeds the lock is acquired and after that, the test is performed again. The second test is needed for avoiding race conditions in case other thread happens to initialize pInstance between the time pInstance was tested and the time the lock was acquired.
Theoretically, this pattern is correct, but in practice is not always true, especially in multiprocessor environments.
Due to this rearranging of writes, the memory as seen by one processor at a time might look as if the operations are not performed in the correct order by another processor. In our case, the assignment to pInstance performed by a processor might occur before the Singleton object has been fully initialized.
After the first call of getInstance() the implementation with pointers (non-smart) needs pointer to that instance in order to avoid memory leaks.

Version 3 – Singleton with smart pointers
Until C++ 11, the C++ standard didn’t have a threading model and developers needed to use external threading APIs (POSIX or OS dependent primitives). But finally C++ 11 standard has threading support.
Unfortunately, the first C++ new standard implementation in Visual C++ 2010 is incomplete and threading support is available only starting with beta version of VS 2011 or the VS 2012 release preview version.

class smartSingleton {
 private:
  static std::mutex _mutex;

  smartSingleton();
  smartSingleton(const smartSingleton& rs);
  smartSingleton& operator=(const smartSingleton& rs);

 public:
  ~smartSingleton();

  static std::shared_ptr& getInstance() {
    static std::shared_ptr instance = nullptr;

    if (!instance) {
      std::lock_guard lock(_mutex);

      if (!instance) {
        instance.reset(new smartSingleton());
      }
    }

    return instance;
  }

  void demo() {
    std::cout << "smart pointers # next - your code ..." << std::endl;
  }
};

As we know, in C++ by default the class members are private. So, our default constructor is private too. I added here in order to avoid misunderstanding and explicitly adding to public / protected.
Finally, feel free to use your special instance (singleton):

// Version 1
std::shared_ptr p = smartSingleton::getInstance(); // cache instance pointer
p->demo();

// Version 2
std::weak_ptr pw = smartSingleton::getInstance(); // cache instance pointer
pw.lock()->demo();

// Version 3
smartSingleton::getInstance()->demo();

And no memory leaks emotion… 🙂
Multiple threads can simultaneously read and write different std::shared_ptr objects, even when the objects are copies that share ownership.
But even this implementation using double checking pattern but is not optimal to double check each time.


Version 4 – Thread safe singleton C++ 11
To have a thread safe implementation we need to make sure that the class single instance is locked and created only once in a multi-threaded environment.
Fortunately, C++ 11 comes in our help with two new entities: std::call_once and std::once_flag. Using them with a standard compiler we have the guaranty that our singleton is thread safely and no memory leak.
Invocations of std::call_once on the same std::once_flag object are serialized.
Instances of std::once_flag are used with std::call_once to ensure that a particular function is called exactly once, even if multiple threads invoke the call concurrently.
Instances of std::once_flag are neither CopyConstructible, CopyAssignable, MoveConstructible nor MoveAssignable.

Here it is my proposal for a singleton thread safe implementation in C++ 11:

class safeSingleton {
  static std::shared_ptr<safeSingleton> instance_;
  static std::once_flag only_one;

  safeSingleton(int id) {
    std::cout << "safeSingleton::Singleton()" << id << std::endl;
  }

  safeSingleton(const safeSingleton& rs) { instance_ = rs.instance_; }

  safeSingleton& operator=(const safeSingleton& rs) {
    if (this != &rs) {
      instance_ = rs.instance_;
    }

    return *this;
  }

 public:
  ~safeSingleton() { std::cout << "Singleton::~Singleton" << std::endl; }

  static safeSingleton& getInstance(int id) {
    std::call_once(
        safeSingleton::only_one,
        [](int idx) {
          safeSingleton::instance_.reset(new safeSingleton(idx));

          std::cout << "safeSingleton::create_singleton_() | thread id " + idx
                    << std::endl;
        },
        id);

    return *safeSingleton::instance_;
  }

  void demo(int id) {
    std::cout << "demo stuff from thread id " << id << std::endl;
  }
};

std::once_flag safeSingleton::only_one;
std::shared_ptr<safeSingleton> safeSingleton::instance_ = nullptr;

The parameter to getInstance() was added for demo reasons only and should be passed to a new proper constructor. As you can see, I am using a lambda instead normal method.
This is how I tested my safeSingleton and smartSingleton classes.

std::vector v;
int num = 20;

for (int n = 0; n < num; ++n) {
  v.push_back(
      std::thread([](int id) { safeSingleton::getInstance(id).demo(id); }, n));
}

std::for_each(v.begin(), v.end(), std::mem_fn(&std::thread::join));

// Version 1
std::shared_ptr<smartSingleton> p = smartSingleton::getInstance(
    1);  // cache instance pointer p->demo("demo 1");

// Version 2
std::weak_ptr<smartSingleton> pw = smartSingleton::getInstance(2);  // cache instance pointer
pw.lock()->demo(2);

// Version 3
smartSingleton::getInstance(3)->demo(3);

So I create 20 threads and I launch them in parallel (std::thread::join) and each thread accesses getInstance() (with a demo id parameter). Only one of the threads that is trying to create the instance succeeds.
Additionally, if you’re using a C++11 100% compiler you could also delete the copy constructor and assignment operator. This will allow you to obtain an error while trying to use such deleted members.

Other comments
I tested this implementation on a machine with Intel i5 processor (4 cores). If you see some concurrent issues in this implementation please fell free to share here. I am open to other good implementations, too.
An alternative to this approach is creating the singleton instance of a class in the main thread and pass it to the objects which require it. In case we have many singleton objects this approach is not so nice because the objects discrepancies can be bundled into a single ‘Context’ object which is then passed around where necessary.

Update: According to Boris’s observation I removed std::mutex instance from safeSingleton class. This is not necessary anymore because std::call_once is enough to have thread safe behavior for this class.

Update2: According to Ervin and Remus’s observation, in order to make things clear I simplified the implementation version 3 and this is not using std::weak_ptr anymore.

References:
just::thread – Anthony Williams – Just Software Solutions Ltd
C++ and the Perils of Double-Checked Locking by Scott Meyers and Andrei Alexandrescu
Modern C++ Design: Generic Programming and Design Patterns Applied by Andrei Alexandrescu