bshoshany/thread-pool

deadlock[BUG]

wjr-z opened this issue · 4 comments

wjr-z commented

Deadlock caused by reset
It is necessary to lock running during reset
Otherwise, if the thread is in the process of judging the end of running, but has not yet waited, the running has been modified and has been notified_ All, it will deadlock
The probability of deadlock is very low, but it may still occur.
On my local machine, a deadlock occurred when using GCC12.2 for testing

BS::thread_pool pool;
void func() {
	pool.pause();
	for (int i = 0; i < 32; ++i) {
		pool.push_task([]() {return 0; });
	}
	pool.unpause();
	for (int i = 0; i < 32; ++i) {
		pool.reset();
	}
	pool.wait_for_tasks();
}

int main() {
	for (int i = 0; i < 1e3; ++i) {
		func();
		printf("%d ", i);
	}
	printf("done\n");
	return 0;
}

Thanks for opening this issue, @wjr-z. I will take a look and try to fix this. However, I'm putting this at a lower priority compared to other issues, because this only happens if you call reset() 32 times in a row, which isn't really a typical use scenario.

I can see that @Antares0982 has written a workaround, but his fork seems to work differently from mine, so I'm not sure it translates back. Also, his solution seems to be a bit complicated, and I hope there may be an easier way to solve this.

I'm open to suggestions regarding simple solutions!

Add

    fflush(stdout);

after the first printf() to make this more obvious.

@bshoshany the 32 times in a row just makes it happen more quickly to make it repeatable. If you just change the 32 to 2 it'll just take a more iterations (so change 1e3 to 1e6). If you remove the push_task altogether then a single reset reliably deadlocks as well, though on my machine it can take 70,000 iterations.

I strongly suspect this has the same root cause as #107

@bshoshany I understand you have more pressing things than working on free software (like teaching) but let's avoid terms like "lower priority" for things that literally break your users' software. These deadlocks are roughly one in a thousand, and that is not rare.

@wjr-z see #93 for a hacky fix that I'm currently using.

@alugowski thanks for the information. I said it's lower priority because the code appears to be very artificial and I don't see this issue breaking any real-life software, but if you believe this can also happen in real-life applications, I will move this to a higher priority. Like I said in #107, it's important to me that the thread pool is "mathematically" free of deadlocks, even in artificial examples like this one, so I do intend to work hard on this until I find a solution.

Closed as resolved by PR #108 (will be included in v3.4.0).