Listing 1 Sample source code to be debugged
#include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <unistd.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int iCounter = 0; void incrementCounter() { /* * Increment iCounter by 1 using an inconsistent state protected by * the mutex */ pthread_mutex_lock(&mutex); iCounter += 9999; iCounter -= 9998; pthread_mutex_unlock(&mutex); usleep(200); } void * myThread(void *arg) { /* Unused argument */ arg; while (1) incrementCounter(); } int main() { pthread_t tid = 0; int i = 0; char *pLeak = NULL; /* Hereunder is a small memory leak */ pLeak = malloc(100); /* Create a thread */ pthread_create(&tid, NULL, myThread, NULL); /* * Display the counter value when the mutex is acquired every 500 ms * until it reaches 100 */ while (i < 100) { pthread_mutex_lock(&mutex); printf("iCounter=%d\n", i = iCounter); pthread_mutex_unlock(&mutex); usleep(500); } /* Cancel the computing worker thread */ pthread_cancel(tid); return 0; }