Tag Archives: class

Histogram loop time

C++ Class for Loop Time Histogram Statistics

Overview

In this post, I am sharing a C++ Class for Loop Time Histogram. The class measures the loop time and provides its histogram statistics. It is very easy to use and portable. The class provides file output and file output + screen output features.

@Update 04/08/2020: Now histogram is printed in terminal for quick review. For details see the result picture below.

How to use

Simply include the class object, and add a function at the beginning of the loop. Finally, execute a function outputting the result.

Example Code

This example code will execute rand() function multiple times in a loop and measure its loop time.

#include <iostream>
#include <random>
#include "loop_time_stats.h"

using namespace std;

int main()
{
    loop_time_stats l("stats.txt",loop_time_stats::output_mode::fileout_and_screenout);

    for (int i=0;i<100000;i++){
        l.loop_starting_point();
        for (int j=0;j<5000;j++){
            int k =rand();
        }
    }
    l.store_loop_time_stats();
    return 0;
}

Result

C++ Class for Loop Time Histogram

The program also saves the result in a text file. I have plotted its result in Excel. The results are shown in the pictures below:

C++ Class for Loop Time Histogram

Download

You can download the class, example code, and excel files in the link below:

https://drive.google.com/drive/folders/1jMfjhO4zbqBd0Y_ozbGH7zhT0HMnUaZF?usp=sharing

Why did I develop this one?

It is critical for real-time applications to have consistent loop-times with low jitter. There are many different ways of measuring the loop time and generating the histogram (e.g., see cyclictest ( https://github.com/LITMUS-RT/cyclictest ) ), many of those are not portable.

While developing a program, these loop-time measurement codes need to be sometimes activated and sometimes deactivated. Finally they need to be removed at release. It means the code needs to be portable. Object-oriented programming (OOP) concept with C++ class is well suited for this purpose.

Thus, I have embedded all of the sophisticated-looking codes in the class and left only “init”, “loop_start_point”, and “save”. With this simple structure, the user would be easily manage the code with a minimal footage.

Reference

Good luck to your project, and if you have any questions or ideas to improve the codes, please leave a comment. Bye!

Shared Memory IPC Ping-pong Sequence

Overview

In this post, I am sharing an example of IPC communication with a class using shared memory.

Two processes runs together, and their applications sequentially running. The end of each loop is marked at a shared memory with a “go-flag”. Once the other process see the end-of-the-loop flag, “go-flag”, the process continues the task.

Shared Memory IPC Class

I wrote this class to make the shared memory programming more portable. What you need to do is only to change the struct called “shared_memory_packet. You will see how to use this class in the examples of the next section. You can see the code of “shared_memory_base.h” and “shared_memory_base.cpp” below:

#ifndef SHARED_MEMORY_BASE_H
#define SHARED_MEMORY_BASE_H

#include <sys/ipc.h>
#include <sys/shm.h>

#define DEFAULT_KEY_ID  5700        // default key for shared memory

class shared_memory_base
{
    struct shared_memory_packet {
        float analog_input[16];
        bool go_flag_second_loop = 1;
        bool go_flag_first_loop = 1;
    };

private:
    key_t key;
    int shmid = 0;
public:
    shared_memory_base();
    ~shared_memory_base();

    shared_memory_packet* data;
    void init();
    void change_shared_memory_key(key_t k){key= k;} // only use this function before init
    void detach_shared_memory();
};

#endif // SHARED_MEMORY_BASE_H
#include "shared_memory_base.h"

shared_memory_base::shared_memory_base()
{
    key = ftok("shmfile",DEFAULT_KEY_ID);
}

shared_memory_base::~shared_memory_base(){
    detach_shared_memory();
}

void shared_memory_base::init(){
    // shmget returns an identifier in shmid
    shared_memory_packet temp;
    shmid = shmget(key, sizeof(temp),0666|IPC_CREAT);
    // shmat to attach to shared memory
    data = (shared_memory_packet*) shmat(shmid,(void*)0,0);
}

void shared_memory_base::detach_shared_memory(){
    shmdt(data);
    shmctl(shmid,IPC_RMID,nullptr);
}

Ping-pong Sequence between Two Processes

In this example, “first_app.cpp” the number of an integer variable incrementally, and change the “go_flag_second_loop” to be one. In “second_app.cpp” the number of an integer variable is reduced, and change the “go_flag_first_loop” to be one. With this two go_flags two processes run sequencially.

#include <iostream>
#include <unistd.h>
#include "shared_memory_base.h"

using namespace std;

int main()
{
    shared_memory_base comm;
    comm.init();

    comm.data->analog_input[0] =0;
    comm.data->analog_input[8] =0;

    for (int i=0;i<10;i++){
        while( comm.data->go_flag_first_loop != 1);
        comm.data->analog_input[0] = i;
        cout << "ai[8]: " << comm.data->analog_input[8] << endl;
        comm.data->go_flag_second_loop = 1;
        sleep(1);
    }

    cout << "end of the loop!" << endl;
    comm.detach_shared_memory();
    return 0;
}
#include <iostream>
#include "shared_memory_base.h"

using namespace std;

int main()
{
    shared_memory_base comm;
    comm.init();

    comm.data->analog_input[0] =0;
    comm.data->analog_input[8] =0;
    comm.data->go_flag_first_loop = 1;

    for (int i=0;i<10;i++){
        while( comm.data->go_flag_second_loop != 1);
        comm.data->analog_input[8] = 1000-i;
        cout << "ai[0]: " << comm.data->analog_input[0] << endl;
        comm.data->go_flag_second_loop = 0;
    }

    cout << "end of the loop!" << endl;
    comm.detach_shared_memory();
    return 0;
}

Result

The figures below shows the execution results of two applications.

Execution Result of “First_app”
Execution Result of “Second_app”

Download and Build the Codes

You can download the entire code and can build the code with the command below:

Download link

mkdir build
cd build
cmake ../shared_memory_example
make

More discussion

Concurrency problem is a very well-known and challenging problem. There are many other nice techniques other than this one. Particularly after C++11, the standard C++ has introduced a nice set of concurrent thread and process running functions. In addition, this example is not the best code for efficient applications.

I found a very good reference explaining Concurrency, Parallelism, Threads, Processes, Async and Sync. For the details, read the article in the link below:

https://medium.com/swift-india/concurrency-parallelism-threads-processes-async-and-sync-related-39fd951bc61d

pthread class implemented in C++ inheritance

I am sharing a set of code generating a thread with pthread by taking an advantage of C++ class inheritance.

You can download the code in this link.

Now, the creation of thread in c++ is easier than before with the standard “thread” class. But still “pthread” is more generic and available in various environments. For my case, I need to control the priority of a thread for real-time applications. In this case, pthread is a good selection.

The creation of pthread in a class environment is very common but it needs some careful implementation because it needs a static function. Hence, the inheritance of C++ can simplify the implementation. We can use a base class including the fundamental functions of pthread, and an application class which needs thread can be created by inheriting the base class.

Simply, You can create your application class using thread like below:

#include <iostream>
#include <unistd.h> // for sleep function

#include "basethreadclass.h"

class MyAppThread: public BaseThreadClass{
    void InternalThreadEntry(){
        int i=0;
        while(1){
            std::cout << i++ << " hello from pthread\n";
            usleep(10000);
        }
    };
};

int main(){
    MyAppThread a;
    a.StartInternalThread();
    int i=0;
    while(1){
        std::cout << i++ << " hello from main\n";
        usleep(10000);
    }
    return 0;
}

The base class, “BaseThreadClass” looks like below:

#ifndef BASETHREADCLASS_H
#define BASETHREADCLASS_H

class BaseThreadClass
{
public:
    BaseThreadClass() {/* empty */}
    virtual ~BaseThreadClass() {/* empty */}

    /** Returns true if the thread was successfully started, false if there was an error starting the thread */
    bool StartInternalThread()
    {
        return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
    }

    /** Will not return until the internal thread has exited. */
    void WaitForInternalThreadToExit()
    {
        (void) pthread_join(_thread, NULL);
    }

protected:
    /** Implement this method in your subclass with the code you want your thread to run. */
    virtual void InternalThreadEntry() = 0;

private:
    static void * InternalThreadEntryFunc(void * This) {((BaseThreadClass *)This)->InternalThreadEntry(); return NULL;}
    pthread_t _thread;
};


#endif // BASETHREADCLASS_H

You can compile them with the included cmake file, and execute the application like below:

crop_thead

I hope this post help your project and understanding. Good luck!

Again you can download the codes link.

 

Reference

[1] https://stackoverflow.com/questions/1151582/pthread-function-from-a-class

 

UDP Server C++ Class with a listening thread


DO NOT USE THIS CODE ANY LONGER. TOO MUCH OUTDATED AND BUGGY


I am sharing a code for “UDP Server C++ Class with a listening thread”. In the class “UDPThread”, a thread is running to receive a UDP packet.

<Download>

Just compile a demo program with this command. Then you will understand.

g++ demo_udp_server.cpp UDPThread.cpp -lpthread -o demo_udp_server

This is the result.

Screenshot from 2015-03-04 15:44:40

<Download>

I hope this code helps your project.

-Mok-

Simple C++ Code for Multi Dynamixel Servo Motor Control

Simple C++ Code for Multi Dynamixel Servo Motor Control

 

// this post is updated to eliminate the dependency on QT, 2015.06.26

 

In this post, I am sharing my C++ class to control multi Dynamixel servo motors.

In my case, I am using MX-24f, but most of dynamixel servo motors are using the same protocol. Thus, you can use this code directly. I am attaching all files (dynamixel library and others) to execute a demo program.

<Download>

If you don’t need common files, just use “multi_dnmx_motor.h” and “multi_dnmx_motor.cpp”. For the usage, see “main.cpp” file. It is super easy.  Demo program was made for Linux environment, but Windows uses still can use “multi_dnmx_motor” class

If you don’t know anything about Dynamixel program. Just follow the below.

 

0. Before following this instruction, check if the connection and settings are correct with “RoboPlus Manager” which can be downloaded in Robotis website, >> Support >> Download.

1. Go to “Dynamixel_src” folder.

2. “Make” : It will generate a library and automatically copy the lib. to the library folder.

3. Go to “Multi_Dynamixel_Motor_Control” folder.

4. Open “multi_dnmx_motor.h” file

5. Change “user setting”. You have to set the baud_rate, number of motors, and their motor IDs. Just change defines. (If you don’t know motors’ these values, use “RoboPlus”, a super easy program, and available in the Robotis website, http://support.robotis.com/en/ )

// User setting
#define BAUD_NUM 34 // 1: 1Mbps 34:57142bps
#define NUM_OF_MOTORS 4 // Number of motors

#define MOTOR_ID_1 1 // Motor 1 ID
#define MOTOR_ID_2 2 // Motor 2 ID
#define MOTOR_ID_3 3 // Motor 3 ID
#define MOTOR_ID_4 4 // Motor 4 ID

6.  compile it with this command

” g++ main.cpp multi_dnmx_motor.cpp -I../include -L../lib -ldxl  ”

7. Execute the program.

 

Good luck ^_^

<Download>