/* Include lib */
#include <stdio.h>
#include <pthread.h>

/* Define */
#define MAX_NUM     40

volatile int cnt = 0;

/* API */
void *print_even(void *tid)
{
    while(cnt < MAX_NUM) {
        if ((cnt % 2) == 0)
            printf("%d ", cnt++);
    }
}

void *print_odd(void *tid)
{
    while(cnt < MAX_NUM) {
        if ((cnt % 2) != 0)
            printf("%d ", cnt++);
    }
}

/* Main func interract with user */
int main()
{
    pthread_t tid[2];

    /*
     * Create 2 thread: thread0 print even, thread1 print odd.
     * Because print number continously, 2 thread must wait other before print.
     */
    printf("Array:\n");
    pthread_create(&tid[0], NULL, print_even, NULL);
    pthread_create(&tid[1], NULL, print_odd, NULL);
    
    /* Wait here to avoid main func done will stop code simulation */
    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: