/* 232 problems with threads example. Compile with: * * g++ -O2 -o 232_demo 232_demo.c -lpthread * * Run on a dual core machine. Adjust the number of threads NTHREADS. * Adjust the atomicity of the increment in "do_stuff" (i.e., uncomment different versions). */ /* Linux with glibc: * _REENTRANT to grab thread-safe libraries * _POSIX_SOURCE to get POSIX semantics */ #ifdef __linux__ # define _REENTRANT # define _POSIX_SOURCE #endif /* Hack for LinuxThreads */ #ifdef __linux__ # define _P __P #endif #include #include /* for strerror() */ #include #include #include #define NTHREADS 1 #define errexit(code,str) \ fprintf(stderr,"%s: %s\n",(str),strerror(code)); \ exit(1); volatile unsigned counter = 0; /******** this is the thread code */ void *do_stuff(void * arg) { for (int i = 0 ; i < 200000000/NTHREADS ; ++ i) { ++ counter; // asm ("incl counter"); // asm ("lock incl counter" : : "g" (&counter)); } return arg; } /******** this is the main thread's code */ int main(int argc,char *argv[]) { int worker; pthread_t threads[NTHREADS]; /* holds thread info */ int ids[NTHREADS]; /* holds thread args */ int errcode; /* holds pthread error code */ int *status; /* holds return code */ /* create the threads */ for (worker=0; worker