Pithikos/C-Thread-Pool

Bug when compiled with optimization?

powfagged opened this issue · 1 comments

If you compile thpool.c with optimization it seems to hang.

To see this, edit tests/threadpool and change the line
gcc src/conc_increment.c ../thpool.c -pthread -o test
to
gcc -g -O src/conc_increment.c ../thpool.c -pthread -o test
Then when you run ./threadpool, it hangs at

$ gdb -p 22284 ./test
0x00000000004011c5 in thpool_init (num_threads=4) at ../thpool.c:150
150 while (thpool_p->num_threads_alive != num_threads) {}
(gdb) p thpool_p->num_threads_alive
$1 = 4
(gdb) p num_threads
$2 = 4

This is with gcc-4.8.3.

If I change thpool.c, adding "volatile",

typedef struct thpool_{
    thread**   threads;                  /* pointer to threads        */
    volatile int num_threads_alive;        /* threads currently alive   */
    volatile int num_threads_working;      /* threads currently working */
    pthread_mutex_t  thcount_lock;       /* used for thread count etc */
    jobqueue*  jobqueue_p;               /* pointer to the job queue  */    
} thpool_;

That seems to fix it, though it might be worth compiling the other tests with optimization to see if everything still works ok.

Thank you for your input and the fixes! I re-factored the tests now so all tests can be run with or without optimization. You can run all tests with an optimized binary by running ./optimized_compile.sh. I ran the tests and your fix seems to work nice for all test cases.

Thanks again :)