Fix bug
The function can return negative values (i.e., -1) to indicate error. This is not intended.
There is a more subtle data race. Since the function is called concurrently, the order of adding tasks into the queue could be A->A->B->A->B->B. Every thread has its own stack. Expecting 3 tasks to be processed from the A thread, it could continue without having processed the 3 tasks, but the tasks A->A->B, instead of A->A->A.