RTAI实时线程与非实时线程如何通过实时信号量实现同步?

#include <stdio.h>
#include <pthread.h>
#include <rtai_sched.h>
#include <rtai_sem.h>

// 定义全局的信号量变量
    SEM *sem = NULL; 
    unsigned long sem_name = 10; // 信号量的名称
// 非实时线程 线程1执行的函数
void* thread1_func(void* arg) {
    printf("Thread 1 executing...\n");
    if (sem != NULL) 
    {
        // 等待信号量
        if (rt_sem_wait(sem) == 0) {
            printf("Thread 1 acquired the semaphore.\n");
            // 释放信号量
            rt_sem_signal(sem);
        } else {
            printf("Thread 1 failed to acquire the semaphore.\n");
        }
    }
    printf("Thread 1 exiting...\n");
    return NULL;
}


// 实时线程 线程2执行的函数
void* thread2_func(void* arg)
{
    int tick =  3;
    RT_TASK* task = rt_task_init_schmod(nam2num("rtai"), 0, 0, 0, SCHED_FIFO, 255);
    mlockall(MCL_CURRENT | MCL_FUTURE);
    RTIME interval = nano2count(tick * 1000);
    RTIME expected = rt_get_time() + 100 * interval;
    rt_task_make_periodic(task, expected, interval);
    rt_make_hard_real_time();
    
    printf("Thread 2 executing...\n");
    if (sem != NULL) 
    {
        // 等待信号量
        if (rt_sem_wait(sem) == 0) {
            printf("Thread 2 acquired the semaphore.\n");
            // 释放信号量
            rt_sem_signal(sem);
        } else {
            printf("Thread 2 failed to acquire the semaphore.\n");
        }
    }
    printf("Thread 2 exiting...\n");
    rt_task_delete(task);
    return NULL;
}
int main() {
    sem = rt_sem_init(sem_name, 1);
    // 打印初始信号量值
    printf("Initial semaphore opaque: %p\n", sem);
    //printf("Initial semaphore opaque: %d\n", sem->opaque);
    printf("sem_name: %lu\n", sem_name);
    
    // 创建线程1
    pthread_t thread1;
    if (pthread_create(&thread1, NULL, thread1_func, NULL) != 0) {
        printf("Failed to create thread 1.\n");
        return 1;
    }
    pthread_t thread2;
    if (pthread_create(&thread2, NULL, thread2_func, NULL) != 0) {
        printf("Failed to create thread 2.\n");
        return 1;
    }
    
    usleep(1000000);
    
    #if 1
    // 等待线程1完成
    if (pthread_join(thread1, NULL) != 0) {
        printf("Failed to join thread 1.\n");
        return 1;
    }


    // 等待线程2完成
    if (pthread_join(thread2, NULL) != 0) {
        printf("Failed to join thread 2.\n");
        return 1;
    }
    #endif
    // 删除信号量
    if (sem != NULL) 
    {
         printf("rt_sem_delete...\n");
         rt_sem_delete(sem);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值