You need to read up on threads properly, because you are completely misinterpreting how they work.

If multiple thread threads act on the same data concurrently, the result is a race condition (anything can happen, depending on which thread affects the data when, whether the operating system causes threads to preempt each other). Threads do not self-synchronise amongst themselves.

In your calls of pthread_create(), you are providing the same pointer (P) to every thread. That means all threads act on the same data concurrently.

Either your threads need to be passed different data (e.g. each thread is passed its own P, which is not shared with other threads) or they need to synchronise access to it (e.g. each thread cooperates with every other thread, and waits until it has exclusive access to the data) using synchronisation primitives (mutexes, critical sections, etc).