如何在Contiki中运行并行进程

时间:2019-12-22 10:31:20

标签: contiki contiki-process

我想创建两个应该并行执行的进程。我正在尝试以下代码:

PROCESS(hello_world_process, "Hello world process");
PROCESS(hello_world_process2, "Hello world process2");
AUTOSTART_PROCESSES(&hello_world_process,&hello_world_process2);
/*---------------------------------------------------------------------------*/
int i;
void program1(void)
{
    for (i=0;i<10;i++)
    {
        printf("%d from 1st process\n",i);  
    }
}

void program2(void)
{
    for (i=0;i<10;i++)
    {
        printf("%d from IIund process\n",i);    
    }
}


PROCESS_THREAD(hello_world_process, ev, data)
{
    PROCESS_BEGIN();
    program1();
    PROCESS_END();
}
PROCESS_THREAD(hello_world_process2, ev, data)
{
    PROCESS_BEGIN();
    program2();
    PROCESS_END();
}

但是第二个过程是在第一个过程完成之后开始的。

输出:

Contiki-list-1532-g2ca33d4 started with IPV6, RPL
Rime started with address 1.2.3.4.5.6.7.8
MAC nullmac RDC nullrdc NETWORK sicslowpan
Tentative link-local IPv6 address fe80:0000:0000:0000:0302:0304:0506:0708
0 from 1st process
1 from 1st process
2 from 1st process
3 from 1st process
4 from 1st process
5 from 1st process
6 from 1st process
7 from 1st process
8 from 1st process
9 from 1st process
0 from IIund process
1 from IIund process
2 from IIund process
3 from IIund process
4 from IIund process
5 from IIund process
6 from IIund process
7 from IIund process
8 from IIund process
9 from IIund process

我如何并行执行这两个过程?

1 个答案:

答案 0 :(得分:1)

Contiki processes基于Dunkel的protothreads:http://dunkels.com/adam/pt/

因此,它们具有一些细节:

  1. 它们是协作多线程的一种形式。这意味着 源代码应明确指出在哪一点产生 执行;这不是抢占式多线程,而是在其中切换 线程之间会自动发生。
  2. 它们是用C语言实现的,该语言不 开箱即用的支持,因此所有protothread操作都是 限于主要过程功能。从中调用的函数 主过程函数不能产生,只有主函数可以产生。
  3. 这些进程共享一个公共堆栈。线程局部的概念 (局部流程)变量不存在; static变量必须是 而是用来保留跨多个调用的值 单一过程。

您的代码具有所有这些问题:

  • 代码中没有明确的产量
  • 您期望(隐式)收益来自子功能
  • 变量i实际上是全局变量,因此它将在多个进程之间共享-可能不是您想要的。

请尝试以下代码:

PROCESS_THREAD(hello_world_process, ev, data)
{
    static int i;
    PROCESS_BEGIN();
    for (i=0;i<10;i++)
    {
        printf("%d from 1st process\n",i);  
        process_poll(&hello_world_process2);
        PROCESS_YIELD();
    }
    PROCESS_END();
}

PROCESS_THREAD(hello_world_process2, ev, data)
{
    static int i;
    PROCESS_BEGIN();
    for (i=0;i<10;i++)
    {
        printf("%d from IIund process\n",i);
        process_poll(&hello_world_process);
        PROCESS_YIELD();
    }
    PROCESS_END();
}