//* Threads in Windows - Variations - threads have separate local vars *

#ifdef _MSC_VER // for MS Visual Studio compilers - to allow "classic" insecure printf and scanf #define _CRT_SECURE_NO_WARNINGS #endif #include <stdio.h> #include <stdlib.h> #include <windows.h> typedef struct { unsigned long int duration; unsigned long int increment; char print_debug; } parameters_t; volatile unsigned long int GlobalSum; /* data is shared by the thread(s) */ /* the threads runs in these separate functions */ DWORD WINAPI Summation(PVOID Param) { parameters_t * P = (parameters_t*) Param; unsigned long int i, j; // local variables might be quicker to access and/or easier to optimize for a compiler const unsigned long int upper = P->duration; const unsigned long int inc = P->increment; const char prn = P->print_debug; for (i = 1; i <= 1000; i++) { for (j = 1; j <= upper; j++) { GlobalSum+=inc; } printf("%c", prn); } return 0; } int main(int argc, char *argv[]) { DWORD ThreadId[2]; HANDLE ThreadHandle[2]; parameters_t ThreadParam1; parameters_t ThreadParam2; long int Param; // do some basic error checking if (argc != 2) { fprintf(stderr,"Use: \"%s <DURATION>\"\n or enter the duration now\n\n" "Loop count = ", argv[0]); fscanf(stdin," %ld", &Param); // <- MSVS compiler warning is irrelevant here and can be avoided } else { Param = atol(argv[1]); } if (Param < 0) { fprintf(stderr, "an integer >= 0 is required \n"); return -1; } ThreadParam1.duration = Param; ThreadParam1.increment = +1; ThreadParam1.print_debug = 'x'; ThreadParam2.duration = Param; ThreadParam2.increment = -1; ThreadParam2.print_debug = 'o'; // create the thread ThreadHandle[0] = CreateThread(NULL, 0, Summation, &ThreadParam1, 0, &ThreadId[0]); ThreadHandle[1] = CreateThread(NULL, 0, Summation, &ThreadParam2, 0, &ThreadId[1]); WaitForMultipleObjects(2, ThreadHandle, TRUE, INFINITE); CloseHandle(ThreadHandle[0]); CloseHandle(ThreadHandle[1]); if (GlobalSum==0) fprintf(stdout,"sum = %ld\n", GlobalSum); else fprintf(stdout,"sum = %ld (Shouldn\'t it be 0\a?)\n", GlobalSum); return(0); }