This assumes that the tid are always in the same order, what if the order is reversed? What if a third thread gets attached?
Yes, this would not work correctly when the TIDs are reversed or more than two threads are involved. But so was the case before this patch.
The complete fix is more complicated. For example, say thread A attaches to thread B, and thread C attaches to thread D, then thread B attaches to thread C. Now all four threads should have the same input according to my local tests. Then if you detach thread B from thread C, thread C and thread D are still attached, and thread A and thread B are still attached as well. So this would require a rewrite to use trees or graphs with refcount.
So I added the refcount first to fix the application. I think it would be an improvement on top of what we have without major changes. If this is not enough, then I guess I will try to implement it properly when I have time.