开发者

logging last eight character of the thread id?

In my multithreaded program, I am logging process id and thread id. Thread id is generated using pthread_self() function. when I print in hex, generally it has 12 characters out of which first four are always common and I don't want to log them.

What is开发者_开发问答 the best way in C++ to print last 8 characters, I tried to use boost::format but couldn't figure out how to print last 8 characters.

e.g Here printing process id in decimal and thread id in hex.

 std::cout << boost::format("%5d|%8X") %getpid() %pthread_self()

I have made it work with below solution but I don't like the magic number 10000000000

std::cout << boost::format("%5d|%8X") %getpid() %(pthread_self()%10000000000)

NOTE: For simplicity, here I used std::cout. In my application, I use boost::log so if there is a way to do using boost log, that's preferred.

Here is an example: 7f08 is common and doesn't add any value in debugging.

14833|7f084b7fe700

14833|7f084bfff700

14833|7f0850dec700

14833|7f08515ed700

14833|7f0851dee700

14833|7f08525ef700

14833|7f0852df0700

14833|7f08535f1700


Your magic constant should be in hex:

pthread_self() & 0xffffffff

This lets bits in the bottom 8 hex digits pass through unchanged, but sets bits in the higher hex digits to 0. They should then be suppressed, since you haven't specified leading 0 printing.


1) declare a char[13] variable on stack
2) sprintf there your thread id in %x form
3) then if you take a pointer to 4-th element of the array it will be your 8-char string - you can log it via whatever you like


Put the computation in a new function properly named, like last_part_of_thread_id(). Then the code will not look that magic inside such a function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜