Question

I would like to compare a Thread pool with 8 threads (8 threads as there are 8 cores on my system) versus single thread for some set of tasks.

Test 1: Tasks given to Thread pool was to look into a queue (std::queue) and fetch an integer from it and calculate its factorial and display it on screen. So 500 times, I called a function addTask in Thread pool class and added 500 numbers ranging between 1 to 20. So in parallel, integers are added and 8 threads are picking them and running to calculate factorial. Synchronization to queue has been added in thread pool. Took note of time between adding the tasks to Thread pool queue and total completion of all 500 jobs. Lets call this time as T1.

Test 2: Wrote a simple factorial function to calculate the result & display it. Ran a simple loop 500 times, calling the factorial function with numbers ranging from 1 to 20. Took note of time between before and after the loop. Lets call this time as T2.

Interestingly, T2 is always less than T1. How is that possible.

I don't mind sharing the code, in case the above description is not clear.

Was it helpful?

Solution

Thanks to "indeterminately sequenced" and "oakad", the above makes sense. Just to conclude and ensure the understanding, I ran below tests, that proved your thoughts:

  1. In task thread, removed cout code and added code to write the calculated factorial in a new file with arbitrary name. By this the shared resource "displaying to computer screen" is omitted. This resulted in T1 around 10 times less than T2. Did a quick test to write to same file after acquiring lock to it, this resulted in T1>T2, due to share resource.

  2. Removed all the cout and the file i/o, instead of calculating factorial, ran a blind loop a million times in each task thread. This resulted in T1 far less than T2. Due to that fact that there is no shared resource in all the 8 threads.

In case you find me mistaken or need more clarification, please feel free to add.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top