0

Thread pool and lock not working at same time

Hi Please find attached code for thread pool. https://code.sololearn.com/ca18A69A181a It is not showing any output as of now instead of expected output of 100 times Hi If I uncomment code line 116 (obj.addTask(print);) and comment line 117 (obj.addTask(Prepareasks);) in main function, it works. Am i doing something wrong with mutex in Prepareasks function? Why output is not there? Any idea?

9th Mar 2021, 7:31 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 2
It seems that your join call in the destructor either crashes or waits infinitely for the thread to finish execution ( hard to tell on sl ) so the printAll is never reached. Sadly I don't use threads often enough to know of a solution. :( Also you're only gonna get 1 Hi with a set if it does work.
9th Mar 2021, 9:02 AM
Dennis
Dennis - avatar
+ 2
The problem is not that the destructor isn't called, it's that it never finishes. The destructor infinitely waits for the threads to finish execution, that's what join does, which will never happen since the threads themselves are waiting for a task in an infinite loop. You can test yourself by putting a cout inside the destructor's loop and/or after the loop. You'll see that the destructor never finishes and because of that printAll is never reached. The only reason addTask(print) works is because the print function directly prints. But it too suffers from an infinite loop in the destructor.
9th Mar 2021, 2:15 PM
Dennis
Dennis - avatar
0
Hi Dennis , no problem nd thanks for sharing your view. Issue should not be there that is what I feel ... Because my destructor should get called due to scope I wrapped inside threadpool object I used... Still I am not sure why output is not there. yeah, correct that set will not allow duplicate entry..
9th Mar 2021, 10:03 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Oh ok.... thank you so much for detailed explanation.... Now I got the actual issue it seems.... Also wondering that thread joining inside constructor for loop is also not working .... All the sites I have referred to is having join in either destructor or in constructor but with new for loop additional to thread creation for loop.. Seems neither of them working for me nd this problem is far bigger than I felt initially... Again thanks a lot for explaining the root cause
9th Mar 2021, 8:04 PM
Ketan Lalcheta
Ketan Lalcheta - avatar