Sunday, September 04, 2016

C++ Identifying threads with names

In multi-threaded applications, many a times during debugging or logging, we wish to identify the threads by name[functionality ]. Simply printing the executing method name in logs does not help if the functions are common between threads doing different tasks. Also you may want to see the currently running threads from either top or ps in your application.

Here is sample program to tag your threads with proper names. Use prctl defined in <sys/prctl.h> , to get/set thread names. Keep in mind that the name can be up to 16 bytes long only. 

#include <stdio.h>
#include <pthread.h>
#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <sys/prctl.h>

//compile the program with : -lpthread

using namespace std;

void * f1(void *) {

 try{
  prctl(PR_SET_NAME,"Thread_name_f1",0,0,0);
  printf("f1 : Starting sleep\n");
  // ..
  // Code goes here
  // utils();
  // g();
  // ..
 }
 catch(std::string &s){
  char thread_name[17]={0};
  prctl(PR_GET_NAME,thread_name,0,0,0);
  std::cout << "Thread:" << thread_name <<"crashed. Reason:" << s << std::endl;
 }
}

void * f2(void *) {

 try{
      prctl(PR_SET_NAME,"Thread_name_f2",0,0,0);
  printf("f2 : Starting sleep\n");
  // ..
  // Code goes here
  // a();
  // utils();
  // ..
 }
 catch(std::string &s){

  char thread_name[17]={0};
  prctl(PR_GET_NAME,thread_name,0,0,0);
  std::cout << "Thread:" << thread_name <<"crashed. Reason:" << s << std::endl;
 }
}

int main() {
 pthread_t  f1_thread, f2_thread;
 pthread_create(&f1_thread, NULL, f1, NULL);
 pthread_create(&f2_thread, NULL, f2, NULL);

 printf("Main : Starting sleep\n");
 sleep(50);
 pthread_join( f1_thread, NULL);
 pthread_join( f2_thread, NULL);
 printf("Main : Done sleep\n");
 return 0;

}

No comments:

[Windows] Refreshing Environment variable for windows command prompt or Powershell

Sometimes, after installing a package like chocolatey ,or npm packages, it asks you to restart the cmd.exe or powershell window to reload t...