【问题标题】:User-threaded scheduling API on mac OSX using ucontext & signalsmac OSX 上使用 ucontext 和信号的用户线程调度 API
【发布时间】:2015-11-16 08:41:00
【问题描述】:

我正在设计一个具有以下特点的调度算法:

  • 在一个进程中有 2 个用户线程(上下文)(我应该做 3 个线程,但在 osx 上还不行,所以我决定现在让 2 个工作)
  • 使用 SIGALRM 信号抢占式,该信号每 1 秒关闭一次,将控制从一个上下文更改为另一个上下文,并保存在执行切换之前正在运行的上下文的当前状态(寄存器和当前位置)。

我注意到以下内容:

  • ucontext.h 库在 mac osx 上的行为很奇怪,而当它在 Linux 中应用时,它的行为与它应该的完全一样(来自此人链接的示例:http://man7.org/linux/man-pages/man3/makecontext.3.html 在 linux 上完美地工作,而在mac 它在进行任何交换之前因分段错误而失败)。不幸的是,我必须让它在 osx 而不是 linux 上运行。
  • 我设法解决了 osx 上的 swapcontext 错误,方法是使用 getcontext() 和 setcontext() 进行上下文交换。
  • 在我的信号处理函数中,我使用了 sa_sigaction( int sig, siginfo_t *s, void * cntxt ),因为第 3 个变量曾经将其重新转换为 ucontext_t 指针是有关被中断的上下文的信息(即测试后在 Linux 上为 true)但在 mac 上它没有指向正确的位置,因为当我使用它时,我再次遇到分段错误。

我已经为每个上下文设计了我的测试函数,以便在 while 循环中循环,因为我想中断它们并确保它们返回到该函数中的正确位置执行。我已经定义了一个静态全局计数变量,它可以帮助我查看我是否在正确的用户线程中。

最后要注意的是,我发现在测试函数中调用 getcontext() 在我的 while 循环中会不断更新我当前上下文的位置,因为它是空的 while 循环,因此在该上下文的时间调用 setcontext()来使它从适当的地方执行。此解决方案是多余的,因为这些功能将从 API 外部提供。

    #include <stdio.h>
    #include <sys/ucontext.h>
    #include <string.h>
    #include <stdlib.h>
    #include <stdint.h>
    #include <stdbool.h>
    #include <errno.h>

    /*****************************************************************************/
    /*                            time-utility                                   */
    /*****************************************************************************/

    #include <sys/time.h> // struct timeval

    void timeval_add_s( struct timeval *tv, uint64_t s ) {
        tv->tv_sec += s;
    }

    void timeval_diff( struct timeval *c, struct timeval *a, struct timeval *b ) {

        // use signed variables
        long aa;
        long bb;
        long cc;

        aa = a->tv_sec;
        bb = b->tv_sec;
        cc = aa - bb;
        cc = cc < 0 ? -cc : cc;
        c->tv_sec = cc;

        aa = a->tv_usec;
        bb = b->tv_usec;
        cc = aa - bb;
        cc = cc < 0 ? -cc : cc;
        c->tv_usec = cc;

    out:
        return;
    }

    /******************************************************************************/
    /*                              Variables                                    */
    /*****************************************************************************/
    static int count;

    /* For now only the T1 & T2 are used */
    static ucontext_t T1, T2, T3, Main, Main_2;
    ucontext_t *ready_queue[ 4 ] = { &T1, &T2, &T3, &Main_2 };

    static int thread_count;
    static int current_thread;

    /* timer struct */
    static struct itimerval a;
    static struct timeval now, then;

    /* SIGALRM struct */
    static struct sigaction sa;

    #define USER_THREAD_SWICTH_TIME 1

    static int check;

    /******************************************************************************/
    /*                                 signals                                    */
    /*****************************************************************************/

    void handle_schedule( int sig, siginfo_t *s, void * cntxt ) {
        ucontext_t * temp_current = (ucontext_t *) cntxt;

        if( check == 0 ) {
            check = 1;
            printf("We were in main context user-thread\n");
        } else {
            ready_queue[ current_thread - 1 ] = temp_current;
            printf("We were in User-Thread # %d\n", count );
        }

        if( current_thread == thread_count ) {
            current_thread = 0;
        }
        printf("---------------------------X---------------------------\n");

        setcontext( ready_queue[ current_thread++ ] );

    out:
        return;
    }

    /* initializes the signal handler for SIGALARM, sets all the values for the alarm */
    static void start_init( void ) {
        int r;

        sa.sa_sigaction = handle_schedule;
        sigemptyset( &sa.sa_mask );
        sa.sa_flags = SA_SIGINFO;

        r = sigaction( SIGALRM, &sa, NULL );
        if( r == -1 ) {
            printf("Error: cannot handle SIGALARM\n");
            goto out;
        }

        gettimeofday( &now, NULL );
        timeval_diff( &( a.it_value ), &now, &then );

        timeval_add_s( &( a.it_interval ), USER_THREAD_SWICTH_TIME );
        setitimer( ITIMER_REAL, &a, NULL );

    out:
        return;
    }

    /******************************************************************************/
    /*                      Thread Init                                           */
    /*****************************************************************************/

    static void thread_create( void * task_func(void), int arg_num, int task_arg ) {
        ucontext_t* thread_temp = ready_queue[ thread_count ];

        getcontext( thread_temp );

        thread_temp->uc_link = NULL;
        thread_temp->uc_stack.ss_size = SIGSTKSZ;
        thread_temp->uc_stack.ss_sp = malloc( SIGSTKSZ );
        thread_temp->uc_stack.ss_flags = 0;

        if( arg_num == 0 ) {
            makecontext( thread_temp, task_func, arg_num );
        } else {
            makecontext( thread_temp, task_func, arg_num, task_arg );
        }

        thread_count++;

    out:
        return;
    }

    /******************************************************************************/
    /*                            Testing Functions                               */
    /*****************************************************************************/

    void thread_funct( int i ) {

        printf( "---------------------------------This is User-Thread #%d--------------------------------\n", i );
        while(1) { count = i;} //getcontext( ready_queue[ 0 ] );}

    out:
        return;
    }

    void thread_funct_2( int i ) {
        printf( "---------------------------------This is User-Thread #%d--------------------------------\n", i );
        while(1) { count = i;} //getcontext( ready_queue[ 1 ] ); }

    out:
        return;
    }

    /******************************************************************************/
    /*                               Main Functions                               */
    /*****************************************************************************/

    int main( void ) {
        int r;
        gettimeofday( &then, NULL );

        thread_create( (void *)thread_funct, 1, 1);
        thread_create( (void *)thread_funct_2, 1, 2);

        start_init();

        while(1);

        printf( "completed\n" );

    out:
        return 0;
    }
  • 我在这里做错了什么?我必须稍微改变一下才能在 Linux 上正确运行它并且在 OSX 上运行适用于 Linux 的版本会导致分段错误,但为什么它会在那个操作系统上运行而不是这个?
  • 这是否与我在每个上下文中分配的堆栈大小有关?
  • 我应该为我的信号分配一个堆栈空间吗? (它说如果我不这样做,它会使用默认堆栈,如果我这样做并没有真正的影响)?
  • 如果在 mac osx 上使用 ucontext 永远不会给出可预测的行为,那么在 osx 上实现用户线程的替代方法是什么?我尝试使用 tmrjump 和 longjmp 但我遇到了同样的问题,即当上下文在执行某个函数的过程中被中断时,我如何才能获得该上下文被中断的确切位置以便继续我下一次中断的地方时间?

【问题讨论】:

  • OS X 基于 BSD UNIX; Linux 是一个独立的实现。您应该查看POSIX docs,而不是依赖 Linux 手册页来满足您的行为期望,这两种实现都应该遵守。
  • 另外,如果你只关心 OS X,那么OS X-specific docs 是合理的。
  • 您的线程函数调用getcontext() 很可疑。他们不应该这样做,而且这样做实际上可能会导致问题。
  • 就我的知识和研究能力而言,没有办法实现当前标准确保正确行为的用户上下文线程抢占。诸如您尝试实现的基于信号的方法是最有可能的候选者,但是这些天所需的行为(恢复作为第三个参数传递给信号处理程序的上下文)具有未指定的行为。事实上,现在整个用户上下文框架已经过时了。
  • @JohnBollinger 它不应该在我的线程函数中调用 getcontext()。我刚刚编辑了代码并修复了它。我之前测试的时候有这个。这是导致段错误的实现。此外,使用 Linux 手册、POSIX 手册或特定于 OSX 的代码并没有什么不同,因为它们都提供了关于 ucontext.h 的几乎相同的信息

标签: c osx-yosemite scheduler ucontext user-thread


【解决方案1】:

所以经过几天的测试和调试,我终于得到了这个。我不得不深入研究 ucontext.h 的实现,并发现了 2 个操作系统之间的差异。事实证明 ucontext.h 的 OSX 实现与 Linux 的不同。例如,在 ucontext_t 结构中的 mcontext_t 结构,其中 n=通常保存每个上下文的寄存器(PI、SP、BP、通用寄存器...)的值,在 OSX 中被声明为指针,而在 Linux 中则不是。需要特别设置顶部的其他一些差异是上下文的堆栈指针 (rsp) 寄存器、基指针 (rbp) 寄存器、指令指针 (rip) 寄存器、目标索引 (rdi) 寄存器......所有这些都必须在每个上下文的开始/创建以及第一次返回之后正确设置。我还创建了一个 mcontext 结构来保存这些寄存器,并让我的 ucontext_t 结构的 uc_mcontext 指针指向它。完成所有这些之后,我能够使用在 sa_sigaction 信号处理函数中作为参数传递的 ucontext_t 指针(在我将其重新转换为 ucontext_t 之后),以便准确地恢复上次上下文中断的位置。归根结底,这是一件混乱的事情。有兴趣了解更多详情的可以私信我。 JJ出来了。

【讨论】:

  • 你能分享你的工作代码吗?
猜你喜欢
  • 2019-01-06
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 2014-02-17
  • 2010-09-19
  • 2012-12-22
  • 1970-01-01
相关资源
最近更新 更多