C++


C/C++: Set and Get the name of a pthread

Naming a pthread using meaningful names, can be a very useful feature for debugging multi-threaded applications as it can make your logs very informative.
For this reason, we are presenting two examples demonstrating the use of names in pthreads.

  • [download id=”3786″]
  • [download id=”3788″]

Example 1: The pthread decides for its name

The following code, creates a pthread which later, it will give itself a meaningful name.

[download id=”3786″]


// #define _GNU_SOURCE is needed for the resolution of the following warnings
//warning: implicit declaration of function ‘pthread_setname_np’ [-Wimplicit-function-declaration]
//warning: implicit declaration of function ‘pthread_getname_np’ [-Wimplicit-function-declaration]
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>
#include <asm/errno.h>
#include <errno.h>
// #include <stdlib.h> is needed for the resolution of EXIT_SUCCESS
#include <stdlib.h>

//The thread name is a meaningful C language string, whose length is restricted to 16 characters, including the terminating null byte.
#define MAX_LENGTH_PTHREAD_NAME (16)

struct thread_info_t
{
    // Used to identify a thread.
    pthread_t thread_id;
};

// This is the thread that will be called by pthread_create() and it will be executed by the new thread.
void *self_named_thread(void *data)
{
    // We know that the input data pointer is pointing to a thread_info_t so we are casting it to the right type.
    struct thread_info_t *thread_info = (struct thread_info_t *) data;

    const int setname_rv = pthread_setname_np(thread_info->thread_id, "Tom Hanks");
    if (setname_rv)
    {
        errno = setname_rv;
        perror("Could not set pthread name");
    }

    char thread_name[MAX_LENGTH_PTHREAD_NAME];
    const int getname_rv = pthread_getname_np(thread_info->thread_id, thread_name, MAX_LENGTH_PTHREAD_NAME);
    if (getname_rv)
    {
        errno = getname_rv;
        perror("Could not get pthread name");
    }
    //This function always succeeds, returning the calling thread's ID.
    const pthread_t tid = pthread_self();
    //Usually pthread_t is defined as follows:
    //typedef unsigned long int pthread_t;
    //so we print pthread_t as an unsigned long int
    fprintf(stdout, "I am thread with ID '%lu', my name is '%s' and I gave me my name by myself\n", tid, thread_name );

    return NULL;
}

int main()
{
    struct thread_info_t thread_info;

    const int create_rv = pthread_create(&(thread_info.thread_id), NULL, &self_named_thread, (void *) &thread_info);
    if (create_rv)
    {
        errno = create_rv;
        perror("Could not create thread");
        return EXIT_FAILURE;
    }
    // The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated.
    const int join_rv = pthread_join(thread_info.thread_id, NULL);
    if (join_rv)
    {
        errno = create_rv;
        perror("Could not join thread");
    }
    return EXIT_SUCCESS;
}

[download id=”3786″]

Example 2: The parent decides for the pthread name

The next code, creates a pthread and the parent gives the thread a meaningful name.

[download id=”3788″]


// #define _GNU_SOURCE is needed for the resolution of the following warnings
//warning: implicit declaration of function ‘pthread_setname_np’ [-Wimplicit-function-declaration]
//warning: implicit declaration of function ‘pthread_getname_np’ [-Wimplicit-function-declaration]
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <pthread.h>
#include <asm/errno.h>
#include <errno.h>
// #include <stdlib.h> is needed for the resolution of EXIT_SUCCESS
#include <stdlib.h>
// #include <unistd.h> is needed for the resolution of unsigned int sleep(unsigned int seconds);
#include <unistd.h>

//The thread name is a meaningful C language string, whose length is restricted to 16 characters, including the terminating null byte.
#define MAX_LENGTH_PTHREAD_NAME (16)

struct thread_info_t
{
    // Used to identify a thread.
    pthread_t thread_id;
};

// This is the thread that will be called by pthread_create() and it will be executed by the new thread.
void *self_named_thread(void *data)
{
    // We know that the input data pointer is pointing to a thread_info_t so we are casting it to the right type.
    struct thread_info_t *thread_info = (struct thread_info_t *) data;

    //Added an artificial delay for the sake of the example.
    //Making sure the parent thread gave the pthread a name.
    sleep(1);

    char thread_name[MAX_LENGTH_PTHREAD_NAME];
    const int getname_rv = pthread_getname_np(thread_info->thread_id, thread_name, MAX_LENGTH_PTHREAD_NAME);
    if (getname_rv)
    {
        errno = getname_rv;
        perror("Could not get pthread name");
    }
    //This function always succeeds, returning the calling thread's ID.
    const pthread_t tid = pthread_self();
    //Usually pthread_t is defined as follows:
    //typedef unsigned long int pthread_t;
    //so we print pthread_t as an unsigned long int
    fprintf(stdout, "I am thread with ID '%lu', my name is '%s' and my parent gave me my name\n", tid, thread_name );

    return NULL;
}

int main()
{
    struct thread_info_t thread_info;

    const int create_rv = pthread_create(&(thread_info.thread_id), NULL, &self_named_thread, (void *) &thread_info);
    if (create_rv)
    {
        errno = create_rv;
        perror("Could not create thread");
        return EXIT_FAILURE;
    }

    const int setname_rv = pthread_setname_np(thread_info.thread_id, "Bob Marley");
    if (setname_rv)
    {
        errno = setname_rv;
        perror("Could not set pthread name");
    }

    // The pthread_join() function suspends execution of the calling thread until the target thread terminates, unless the target thread has already terminated.
    const int join_rv = pthread_join(thread_info.thread_id, NULL);
    if (join_rv)
    {
        errno = create_rv;
        perror("Could not join thread");
    }
    return EXIT_SUCCESS;
}

[download id=”3788″]


C/C++: Change position of bytes 1 and 2 with bytes 3 and 4 in a 32bit unsigned integer

The following function will produce a new 32bit value where bytes 1 and 2 were moved in place of bytes 3 and 4 and vice versa.

[download id=”3642″]

#include <stdio.h>
#include <stdlib.h>

const unsigned int move_bytes_1_2_after_4 (const unsigned int input) {
  //We get the two leftmost bytes and move them to the positions of the two rightmost bytes.
  const unsigned int first_two_bytes = (input >> 16) & 0x0000FFFF;
  //We get the two rightmost bytes and move them to the positions of the two leftmost bytes.
  const unsigned int last_two_bytes = (input << 16) & 0xFFFF0000;
  //We combine the two temporary values together to produce the new 32bit value where bytes 1 and 2 were moved in place of bytes 3 and 4 and vice versa.
  return (first_two_bytes | last_two_bytes);
}

int main(void) {
  const unsigned int value = 0xABCD0123;
  printf ("Original: 0x%08x\n", value);
  const unsigned int modified = move_bytes_1_2_after_4(value);
  printf ("Modified: 0x%08x\n", modified);
  return EXIT_SUCCESS;
}

Executing the above code will produce the following output:

Original: 0xabcd0123
Modified: 0x0123abcd

[download id=”3642″]


C++ How to make cout not use scientific notation

To force cout to print numbers exactly as they are and prevent it from using the scientific notation, we can use the std::fixed I/O manipulator as follows

#include <iostream>

using namespace std;

int main()
{
    std::cout << "The number 0.0001 in fixed:      " << std::fixed << 0.0001 << endl
              << "The number 0.0001 in default:    " << std::defaultfloat << 0.0001 << endl;

    std::cout << "The number 1000000000.0 in fixed:      " << std::fixed << 1000000000.0 << endl
              << "The number 1000000000.0 in default:    " << std::defaultfloat << 1000000000.0 << endl;
return 0;
}

Output

The number 0.0001 in fixed:      0.000100
The number 0.0001 in default:    0.0001
The number 1000000000.0 in fixed:      1000000000.000000
The number 1000000000.0 in default:    1e+09

C++: “undefined reference to” templated class function 6

In case you have a project where you use a templated class that is split in its own header (.h) and source (.cpp) files, if you compile the class, into an object file (.o), separately from the code that uses it, you will get the undefined reference to error at linking.

Lets assume we have Stack.cpp and Stack.h which define a templated stack using vectors. And main.cpp that uses this class after including Stack.h.

If you try to compile these files as mentioned above, one by one, later you will get a linking error saying undefined reference to for the methods of the class.

The code in the template is not sufficient to instruct the compiler to produce the methods that are needed by main.cpp (e.g. Stack<int>::push(...) and Stack<string>::push(...)) as the compiler does not know, while compiling Stack.cpp by itself, the data types it should provide support for.

The reason it allows you to compile these incomplete objects is the following:

  • main.cpp: the compiler will implicitly instantiate the template classes Stack<int> and Stack<string> because those particular instantiations are requested in main.cpp. Since the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp (particularly Stack.h), the compiler will not include complete versions of those functions in main.o and it will expect to find them in another object during linking.
  • Stack.cpp: the compiler won’t compile the instantiations of Stack<int> and Stack<string> neither as there are no implicit or explicit instantiations of them in Stack.cpp nor Stack.h.

So in the end, neither of the .o files contain the actual implementations of Stack<int> and Stack<string> and the linking fails.

Solutions

Solution 1 : Explicitly instantiate the template

At the end of Stack.cpp, you can explicitly instantiate all needed templates.
In our example we would add:


template class Stack<int>;
template class Stack<std::string>;

This will ensure that, when the compiler is compiling Stack.cpp that it will explicitly compile all the code needed for the Stack<int> and Stack<std::string> classes.

Using this method, you should ensure that all the of the implementation is placed into one .cpp file and that the explicit instantation is placed after the definition of all the functions (for example, at the end of the file).

A problem with this method is that it forces you to update the Stack.cpp file each time you want to add support for a new data type (or remove one).

Solution 2 : Move the implementation code into the header file

Move all the source code of Stack.cpp to Stack.h, and then delete Stack.cpp. Using this method you do not need to manually instantiate all possible data types that are needed and thus you do not need to modify code of the class. As a side-effect, if you use the header file in many other source files, it will compile the functions of the header file in each source. This can make compilation slower but it will not create any compilation/linking problems, as the linker will ignore the duplicate implementations.

Solution 3 : Move the implementation code into a new header file and include it in the original header file

Rename Stack.cpp to Stack_impl.h, and then include Stack_impl.h from Stack.h to keep the implementation in a separate file from the declaration. This method will behave exactly like Solution 2.