#if __STDC_VERSION__ < 201112L
#   error Needs a C compiler which support the C11 standard or later!
#elif defined(__STDC_NO_THREADS__)
#   error Needs the C compiler and its runtime library support the C11 thread functions!
#endif

#include <stdio.h>
#include <threads.h>

#ifdef _WIN32
#   include <windows.h>
#else
#   include <unistd.h>
#endif

// 這裡定義兩個全域變數，
// 其中一個是普通的變數，
// 另一個則是 thread-local 型態的變數。
int thread_share_value = 0;
thread_local int thread_local_value = 0;

static
void SleepMs(unsigned ms)
{
#ifdef _WIN32
    Sleep(ms);
#else
    usleep( 1000 * ms );
#endif
}

static
int ThrdFunc1(void *userarg)
{
    SleepMs(500);
    for(int i = 0; i < 5; ++i)
    {
        thread_share_value += 1;
        thread_local_value += 1;

        printf("| Thrd-1:\t%d\t%d\t(+1)\n",
            thread_share_value, thread_local_value);
        SleepMs(1000);
    }

    printf("Thrd-1: Addr. of share_value=%p, local_value=%p\n",
        &thread_share_value, &thread_local_value);

    return 0;
}

static
int ThrdFunc2(void *userarg)
{
    SleepMs(0);
    for(int i = 0; i < 5; ++i)
    {
        thread_share_value += 2;
        thread_local_value += 2;

        printf("| Thrd-2:\t%d\t%d\t(+2)\n",
            thread_share_value, thread_local_value);
        SleepMs(1000);
    }
    printf("\n");

    printf("Thrd-2: Addr. of share_value=%p, local_value=%p\n",
        &thread_share_value, &thread_local_value);

    return 0;
}

int main(int argc, char *argv[])
{
    printf("| Thread\tShare\tLocal\tComment\n");
    printf("|---------------------------------------\n");

    thrd_t thrd1;
    thrd_create(&thrd1, ThrdFunc1, NULL);

    thrd_t thrd2;
    thrd_create(&thrd2, ThrdFunc2, NULL);

    thrd_join(thrd1, NULL);
    thrd_join(thrd2, NULL);

    printf("Thrd-0: Addr. of share_value=%p, local_value=%p\n",
        &thread_share_value, &thread_local_value);

    return 0;
}
