Help to understand spawning of threads

Hi, I try to understand how to use the k_thread_create() to spawn a function (here called spam()) that takes a argument, and then runs with the argument. This code will not build, but what do I have to do to be able to build it? Thanks for any help Slight smile

#include <zephyr/kernel.h>

#define THREAD_STACKSIZE       512

#define THREAD_PRIORITY 4 

#define MY_STACK_SIZE 500
K_THREAD_STACK_DEFINE(my_stack_area, MY_STACK_SIZE);
struct k_thread my_thread_data;

void spam(int *a){
    int b = *a;
    while (1)
    {
        if (b>5){
            return;
        }
        k_sleep(K_MSEC(1000));
        printk("HI: %d\n", b);
        b++;
    }
}

void main(void){
    int c;
    c = 1;
    k_tid_t my_tid = k_thread_create(&my_thread_data, my_stack_area, 
                                    K_THREAD_STACK_SIZEOF(my_stack_area), 
                                    (void)spam(&c), NULL, NULL, NULL, 
                                    THREAD_PRIORITY, 0, K_NO_WAIT);
    k_thread_start(my_tid);
    while (1)
    {
        k_sleep(K_MSEC(1000));
        printk("HI\n");
    }
}

Regards

Elias

  • Hi Elias,

    Your compiler is probably complaining about your use of (void)spam(&c) in k_thread_create() on line 29. Arguments p1, p2 and p3 of k_thread_create() are there for you to provide arguments for your thread entry function. So in this case, all you have to do is move the argument of spam() into the neighbouring argument like so:

    k_tid_t my_tid = k_thread_create(&my_thread_data, my_stack_area, 
                                        K_THREAD_STACK_SIZEOF(my_stack_area), 
                                        spam, &c, NULL, NULL, 
                                        THREAD_PRIORITY, 0, K_NO_WAIT);

    When I do that on my machine, I can see your two threads writing "HI" alternatingly. Hope this helps.

    Best regards,

    Raoul Pathak

Related