如何创建一个简单的实时(RealTime)应用程序

前一篇了解了如何在树莓派上编译安装实时内核,这次给出一个例程,了解如何编写一个简单的应用程序让他跑在实时内核上。

代码如下:

/*                                                                  
 * 使用单个pthread作为RT线程
 */
 
#include 
#include 
#include 
#include 
#include 
#include 
 
void *thread_func(void *data)
{
        /* 这里写你要运行在实时内核上的代码 */
        return NULL;
}
 
int main(int argc, char* argv[])
{
        struct sched_param param;
        pthread_attr_t attr;
        pthread_t thread;
        int ret;
 
        /*内存锁定 */
        if(mlockall(MCL_CURRENT|MCL_FUTURE) == -1) {
                printf("mlockall failed: %m\n");
                exit(-2);
        }
 
        /* 初始化线程属性 (默认) */
        ret = pthread_attr_init(&attr);
        if (ret) {
                printf("init pthread attributes failed\n");
                goto out;
        }
 
        /* 设置特定的堆栈大小  */
        ret = pthread_attr_setstacksize(&attr, PTHREAD_STACK_MIN);
        if (ret) {
            printf("pthread setstacksize failed\n");
            goto out;
        }
 
        /* 设置pthread的调度程序策略和优先级 */
        ret = pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
        if (ret) {
                printf("pthread setschedpolicy failed\n");
                goto out;
        }
        param.sched_priority = 80;
        ret = pthread_attr_setschedparam(&attr, ¶m);
        if (ret) {
                printf("pthread setschedparam failed\n");
                goto out;
        }
        /*使用attr的调度参数 */
        ret = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
        if (ret) {
                printf("pthread setinheritsched failed\n");
                goto out;
        }
 
        /*创建具有指定属性的pthread */
        ret = pthread_create(&thread, &attr, thread_func, NULL);
        if (ret) {
                printf("create pthread failed\n");
                goto out;
        }
 
        /*加入线程并等待它完成 */
        ret = pthread_join(thread, NULL);
        if (ret)
                printf("join pthread failed: %m\n");
 
out:
        return ret;
}

注:编译时需要获取root权限、末尾加上-lpthread
在这里插入图片描述

如何还需进一步了解有关实时应用程序编写的问题,可以参考
https://wiki.linuxfoundation.org/realtime/documentation/howto/applications/start

你可能感兴趣的:(如何创建一个简单的实时(RealTime)应用程序)