next up previous
Next: 5 RT-Linux APIによる実時間タスクのプログラミング Up: 4.3 RT-Linuxのサンプルプログラム Previous: 4.3.4 サンプルプログラム2の解説

4.3.5 サンプルプログラム3の解説

rtモジュールとして実現した例.
void play_sound (int hz, int time) { 
                 //  hz(Hz), time(msec)
    int i, wait, ret, tmp;
    wait = 500*1000/hz;
    
    pthread_make_periodic_np(pthread_self(), 
                             gethrtime(), 
                             wait*1000);

    for (i = 0; i < hz * 2 * time / 1000; ++i) {
        ret = pthread_wait_np();
        tmp = rtl_inb(0x61);
        tmp = (i & 1) ? tmp | 0x02 : tmp & ~0x02;
        rtl_outb(tmp, 0x61);
    }
    rtl_outb((inb(0x61) & ~0x02), 0x61);
}

void *thread_code(void *t)
{
    int i;
    for (i = 0; i < score_index; i++){
        play_sound(score[i].note, 
                   500*4/score[i].length);
    }
    return 0;
}

int init_module(void)
{
    pthread_attr_t attr;
    int ret;

    pthread_attr_init (&attr);
    ret = pthread_create (&task, &attr, 
                          thread_code, NULL);
    return ret;
}

void cleanup_module(void)
{
    pthread_cancel (task);
    pthread_join (task, NULL);
}
モジュールは,ロード時にinit_module()が呼ばれ,アンロード時には cleanup_module()が呼ばれる. 上記のプログラムではモジュールのロード時に呼ばれるinit_module()内で, thread_code()スレッドが生成され,thread_code()スレッド内から play_sound()が実行される.play_sound内では, pthread_make_periodic_np()により周期が設定され for (;;) 文の中の pthread_wait_np() で周期実行となるようwaitする.

generated through LaTeX2HTML. M.Inaba 平成18年5月6日