// Two threads and a mutex: each adds its share to `total`, main joins them // and prints it. What clone, futex and a thread's exit look like to a tracer. #include #include static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; long total; __attribute__((noinline)) static void *work(void *arg) { for (long i = 0; i < 1000; i++) { pthread_mutex_lock(&lock); total += (long)arg; pthread_mutex_unlock(&lock); } return NULL; } int main(void) { pthread_t a, b; pthread_create(&a, NULL, work, (void *)1); pthread_create(&b, NULL, work, (void *)2); pthread_join(a, NULL); pthread_join(b, NULL); printf("total = %ld\n", total); return 0; }