#include #include #include #include pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; void logit(const char *fmt, ...) { va_list args; char buf[1024]; int bytes; buf[sizeof(buf)-1] = '\0'; va_start(args, fmt); bytes = vsnprintf(buf, sizeof(buf)-1, fmt, args); va_end(args); pthread_mutex_lock(&log_mutex); printf("%s", buf); pthread_mutex_unlock(&log_mutex); } pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct TestInfo { void (*Lock)(void); void (*Unlock)(void); int Iterations; int Data; int Increment; }; void NoLock(void) { } void NoUnlock(void) { } void PthreadLock(void) { pthread_mutex_lock(&mutex); } void PthreadUnlock(void) { pthread_mutex_unlock(&mutex); } void * TestThread (void *arg) { struct TestInfo *t = (struct TestInfo *)arg; int i; int *pData = &t->Data; logit("Thread %d starting...\n", pthread_self()); sleep(1); for (i=0; iIterations; ++i) { int tmp; int trand; t->Lock(); srand(46); trand = rand(); srand(46); tmp = t->Data; tmp = tmp + trand - rand(); tmp = tmp + t->Increment; t->Data = tmp; t->Unlock(); } logit("Thread %d done.\n", pthread_self()); return NULL; } main (int argc, char ** argv) { int threadcount = 10; pthread_t tid[10]; int i; struct TestInfo Info; Info.Iterations = 500000; Info.Increment = 3; Info.Data = 0; Info.Unlock = &NoUnlock; Info.Lock = &NoLock; for (i=0; i