• Low Latency C++11 Asynchronous Logging Library.
  • Configurable for output to local file/stdout or both.


#include "WoodyLogger.h"
#include <thread>
#include <unistd.h>

void PrintLogThread() {
    LOG_ERROR("PrintLogThread Join -->");
    LOG_ERROR("PrintLogThread END <---");

int main() {



    return 0;

API Description

Macro Define: WOODY_LOGGER







("file_path_name", is_enalbe_output_to_stdout)








WOODY_LOGGER_INIT("/dev/null", false);



There are 6 log levels as Strong to Week order:








The output format









Benchmark Code Compiling Option And System environment

The benchmark test code is run under my MacBook Pro Laptop:

Total Number of Cores:  4
Threads:                8

Test Code


WoodyLogger and NanoLog are both Compiled under -O2 optimization level.

Benchmark Test Result

ThreadsWoodyLogger(Avg, ns)NanLog(Avg, ns)



Normal Design

What makes the high latency of a Log tool?




Normally the Log tool is designed as following:


WoodyLogger Design

Lock-Free Queue



The WoodyLogger design is going to like the following diagram shows:

Github Reference




Photoed on Oct. 2014







Problem Formulation


House Prices
2104 400
1600 330
2400 369
1416 232
3000 540
\vdots \vdots

We can plot this data:






Function Minimization





For a single training example, this gives the update rule:



Repeat until convergence {


Code Implementation










Now we can implement the Gradient Descent in Matlab:

%GRADIENTDESCENT Performs gradient descent to learn theta
%   taking num_iters gradient steps with learning rate alpha

% Initialize some useful values
m = length(y); % number of training examples

for iter = 1:num_iters
    theta = theta - alpha * delta;





#include <armadillo>
#include <iostream>
#include <stdio.h>

using namespace std;
using namespace arma;

	mat J;
	int m;
	m = y.n_rows;
	return J;

void gradientDescent(const mat&    X,
                     const mat&    y,
                           double  alpha,
                           int     num_iters,
                           mat&    theta)
	mat delta;
	int iter;
	int m ;
	m = y.n_rows;
		theta = theta-alpha*delta ;

int main()
	mat data;
	mat X = data.col(0);
	mat y = data.col(1);
	int m = X.n_elem;
	vec X_One(m);
	X.insert_cols(0, X_One);
	int iterations = 1500 ;
	double alpha = 0.01 ;
	mat J = computeCost(X, y, theta);
	return 0;


The result compared with Octave:




3D  contours of a quadratic function:



UFLDL Tutorial – Linear Regression
Andrew Ng Machine Learning (Coursera)
Gradient Descent (Wiki)
Least Squares (Wiki)
Least mean squares filter
Armadillo Doc
Comparison of linear algebra libraries

My previous post “Use shared_ptr inheritance rightly when design and use interfaces” has an obvious problem: There is a cyclic reference between AbstractSocketImpl and Socket I/O Streams.

typedef shared_ptr<InputStream> InputStreamPtr;
typedef shared_ptr<OutputStream> OutputStreamPtr;
typedef shared_ptr<AbstractSocketImpl> AbstractSocketImplPtr;

class AbstractSocketImpl : public AbstractSocket
    InputStreamPtr    inputStreamPtr;
    OutputStreamPtr   outputStreamPtr;

class SocketInputStream : public InputStream
    AbstractSocketImplPtr socket_impl;

When two class have shared_ptr hold each other, it will cause meory leak because of cyclic reference. When shared_ptr objects of AbstractSocketImpl and SocketInputStream are created the reference count in SocketInputStreamPtr and AbstractSocketImplPtr will count each other, so the refer_cout will be 2 of each.

auto socketImpl = make_shared<AbstractSocketImpl>(address);   //socketImpl.ref_count + 1, now socketImpl.ref_count == 1
auto inputstream = socketImpl->getInputStream();   //socketImpl.ref_count + 1 (caused by inputstream.socket_impl), now socketImpl.ref_count == 2.
//inputstream.ref_count == 2, because inputstream holds one reference and inputstream.socket_impl.inputStreamPtr holds inputstream.

The relationship between AbstractSocketImpl and SocketInputStream should be Composition, which SocketInputStream is initialized from an AbstractSocketImpl. There is no meaning for any operations of SocketInputStream when AbstractSocketImpl is destoried. I was incorrectly making strong reference from AbstractSocketImpl to SocketInputStream, which I was trying to manage the memory life-cycle of SocketInputStream from AbstractSocketImpl and make them high coupling. The SocketInputStream is created by AbstractSocketImpl and my mistake was trying to use a shared_ptr (strong reference) to trace the SocketInputStream object. But in fact, SocketInputStream object is managed by user not AbstractSocketImpl, AbstractSocketImpl‘s responsibility is to make sure creating only ONE SocketInputStream object, but NOT recycling it. So AbstractSocketImpl do not need to HOLD a SocketInputStream, it only need to peek whether the SocketInputStream object it created is still alive, if yes, return the pointer, if not, create the new one from itself. So I use weak_ptr to have weak reference to SocketInputStream. Following is the implementation changes:

typedef weak_ptr<InputStream> InputStreamWeakPtr;
typedef weak_ptr<OutputStream> OutputStreamWeakPtr;

class AbstractSocketImpl : public AbstractSocket
    InputStreamWeakPtr   wkInputStreamPtr;
    OutputStreamWeakPtr  wkOutputStreamPtr;

InputStreamPtr AbstractSocketImpl::getInputStream()
    //return make_shared<SocketInputStream>(shared_from_this());
    if ( wkInputStreamPtr.expired() )
        InputStreamPtr inputstrPtr = make_shared<SocketInputStream>(shared_from_this());
        wkInputStreamPtr = inputstrPtr;
        return inputstrPtr;
    return wkInputStreamPtr.lock();

I was asked a question about calculate the Fibonacci number at the compile time not at run time in C++.

Initially, I have no idea about how to solve this problem, how to make the calculation happen in the compile time? Then the key solution is: Using Template.

Template metaprogramming can make compile-time class generation, and also can perform polymorphism in a static, which is well-known as the Curiously Recurring Template Pattern (CRTP).

So the solution is listed as following:


template<int N>
class Fibonacci {
    enum { value = Fibonacci<N-1>::value + Fibonacci<N-2>::value };

class Fibonacci<1> {
    enum { value = 1 };

class Fibonacci<0> {
    enum { value = 0 };

int main() {
    int i =  Fibonacci<6>::value;
    return i;

Compile it to assembly “g++ -O2 -S Fibonacci_template.cpp


_main:                                  ## @main
## BB#0:
	pushq	%rbp
	.cfi_def_cfa_offset 16
	.cfi_offset %rbp, -16
	movq	%rsp, %rbp
	.cfi_def_cfa_register %rbp
	movl	$8, %eax
	popq	%rbp


You can find: The assembly output (Line 12) is compiled into the exact number of Fibonacci(6) is to be 8.


Firstly I think it may easy going like this way:

//Point Base pointer to an implemented Derrived object
//Class "Derived" inheritances from class "Base"
typedef std::shared_ptr<Base> BasePtr;
BasePtr baseptr(new Derived());
//Then call baseptr->operations




int* ptr = new int;
shared_ptr<int> p1(ptr);


Smart Pointer


#include <memory>
#include <iostream>

struct Good: std::enable_shared_from_this<Good>
    std::shared_ptr<Good> getptr() {
        return shared_from_this();

struct Bad
    std::shared_ptr<Bad> getptr() {
        return std::shared_ptr<Bad>(this);

int main()
    // Good: the two shared_ptr's share the same object

} // UB: double-delete of Bad


 Interface Design





InputStreamPtr AbstractSocketImpl::getInputStream()
    if ( !inputStreamPtr )
        inputStreamPtr = make_shared<SocketInputStream>(shared_from_this());
    return inputStreamPtr;

OutputStreamPtr AbstractSocketImpl::getOutputStream()
    if ( !outputStreamPtr )
        outputStreamPtr = make_shared<SocketOutputStream>(shared_from_this());
    return outputStreamPtr;






The Solution is following:


class AbstractSocketImpl : public AbstractSocket
    std::shared_ptr<AbstractSocketImpl> shared_from_this()



AbstractSocketImplPtr socketImpl = make_shared<AbstractSocketImpl>(address);
InputStreamPtr inputstream = socketImpl->getInputStream();
OutputStreamPtr outputstream = socketImpl->getOutputStream();




The first time I saw this kind of expression, I feel so strange with it:

file_buffer<uint8_t>::open(outputFileName, std::ios::out).then([=](streambuf<uint8_t> outFile) -> pplx::task<http_response>
    *fileBuffer = outFile; 

    // Create an HTTP request.
    // Encode the URI query since it could contain special characters like spaces.
    http_client client(U("http://www.bing.com/"));
    return client.request(methods::GET, uri_builder(U("/search")).append_query(U("q"), searchTerm).to_string());


So what does [=] (typename pram) -> typename { } exactly mean?

It is Lambda expression in C++11. A lambda expression represents a callable unit of code. It can be thought of as an unnamed, inline function. Like any function, a lambda has a return type, a parameter list, and a function body. Unlike a function, lambdas may be defined inside a function. A lamba expression has the form:

[capture list] (parameter list) -> return type { function body }

There is a detailed description of Lambda Expression Syntax on MSDN and CPPReference , I will not explain the syntax of Lambda Expression, I would like to introduce my understanding and usage of Lambda Expression.

As my understanding, Lambda Expression creates an Object of an Unnamed Functor (NOT a Function).

A functor is pretty much just a class which defines the operator(). That lets you create objects which “look like” a function (Stackoverflow):

// this is a functor
struct add_x {
  add_x(int x) : x(x) {}
  int operator()(int y) { return x + y; }

  int x;

// Now you can use it like this:
add_x add42(42); // create an instance of the functor class
int i = add42(8); // and "call" it
assert(i == 50); // and it added 42 to its argument

std::vector<int> in; // assume this contains a bunch of values)
std::vector<int> out;
// Pass a functor to std::transform, which calls the functor on every element
// in the input sequence, and stores the result to the output sequence
std::transform(in.begin(), in.end(), out.begin(), add_x(1));
assert(out[i] == in[i] + 1); // for all i

As we have functor so, why do you need Lambda?

I think one important feature of Lambda is, it can create Anonymous Object, it can be Run On Defined.

Java programmers must be familiar with the code when they create an anonymous class, such expression was not supported in C++.  But Lambda express in C++11 can make a similar achievement. Java Programmers can define an anonymous Thread class:

public class A {
    public static void main(String[] arg)
        new Thread()
            public void run() {


C++ now can directly pass a Lambda express into a function call, cause it just bass an object into that function. The grammar is different from anonymous class in Java:

void fillVector(vector<int>& v)
    // A local static variable.
    static int nextValue = 1;

    // The lambda expression that appears in the following call to
    // the generate function modifies and uses the local static
    // variable nextValue.
    generate(v.begin(), v.end(), [] { return nextValue++; });
    //WARNING: this is not thread-safe and is shown for illustration only

Programmer can directly pass a functor object with the function body expressions into a parameter, the code will run on define.


Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?

This question is much related with Number of 1 Bits

Solution 1:

class Solution {
    uint32_t reverseBits(uint32_t n)
        uint32_t i;
        uint32_t value = 0;
            uint32_t tmp = (uint32_t)(n & ((uint32_t)1 << (31 - i))) ? 1 : 0;
            value |= tmp << i;
        return value;

Solution 2:

uint32_t reverse(uint32_t x)
    x = ((x >> 1) & 0x55555555u) | ((x & 0x55555555u) << 1);
    x = ((x >> 2) & 0x33333333u) | ((x & 0x33333333u) << 2);
    x = ((x >> 4) & 0x0f0f0f0fu) | ((x & 0x0f0f0f0fu) << 4);
    x = ((x >> 8) & 0x00ff00ffu) | ((x & 0x00ff00ffu) << 8);
    x = ((x >> 16) & 0xffffu) | ((x & 0xffffu) << 16);
    return x;



Write a function that takes an unsigned integer and returns the number of ’1′ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11′ has binary representation 00000000000000000000000000001011, so the function should return 3.

The normal solution is mostly like the following:

class Solution {
    int hammingWeight(uint32_t n)
        unsigned int count = 0;
           count += n & 1;
           n >>= 1;
       return count;

 When searching from the stackoverflow, there is an interesting solution:

This is known as the ‘Hamming Weight‘, ‘popcount’ or ‘sideways addition’.


Some CPUs have a single built-in instruction to do it and others have parallel instructions which act on bit vectors. The parallel instructions will almost certainly be fastest, however, the single-instruction algorithms are ‘usually microcoded loops that test a bit per cycle; a log-time algorithm coded in C is often faster’.

A pre-populated table lookup method can be very fast if your CPU has a large cache and/or you are doing lots of these instructions in a tight loop. However it can suffer because of the expense of a ‘cache miss’, where the CPU has to fetch some of the table from main memory.

If you know that your bytes will be mostly 0’s or mostly 1’s then there are very efficient algorithms for these scenarios.


int NumberOfSetBits(int i)
