libretro / libretro-common

Reusable coding blocks useful for libretro core and frontend development, written primarily in C. Permissively licensed.
146 stars 76 forks source link

Wait until there is any work item to be done #207

Closed mobinasri closed 1 year ago

mobinasri commented 1 year ago

This is for handling a rare case when all threads are free without any work (working_cnt == 0) but there exist some work items that are not yet done or not yet started to be processed.

I'm using your code (first I took it from your blog) in my program. It was very useful. However I noticed that when I use 1 or 2 threads the pool thread will finish without any doing any job.I'm calling tpool_wait right after adding all works (I had only one or two work items to add for that specific example) so the function, tpool_wait, locks the mutex prior to any working thread takes the mutex. In that case (!tm->stop && tm->working_cnt != 0) is false so it will not call pthread_cond_wait(&(tm->working_cond), &(tm->work_mutex)) and exit immediately. Then I call tpool_destroy right after that and it will take the mutex and this is all happening before any working thread takes the mutex and does any job. Therefore all jobs are canceled by tpool_destroy. I guess this is only happening when we have low number of works to add. I think this small change can make the code more robust to such rare conditions.