#include #include #include #define N_THREADS 5 /// tls - a variable with storage automatically allocated locally for each /// thread created (i.e. "thread-local storage") static long __thread tls = 100; /** * A simple task to be run in multiple threads, which uses concurrently * accessed thread-local storage. */ void* task(void* arg) { long thread_id = (long)arg; tls = (thread_id % 2); // -> 0, 1, 0, 1, 0 printf(" [task - thread %ld] tls = %ld.\n", thread_id, tls); pthread_exit(NULL); } // Forward decls void launch_tasks(pthread_t* threads); void end_tasks(pthread_t* threads); int main() { pthread_t threads[N_THREADS]; printf("[main] begin: tls = %ld\n", tls); launch_tasks(threads); end_tasks(threads); printf("[main] end: tls = %ld\n", tls); return 0; } /** * Run task in separate thread, using pthread_create. Exits if pthread_create * returns non-zero. */ void launch_tasks(pthread_t* threads) { for (size_t ctr=0; ctr