Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Whenever threads come into play, there are bounded to be shared memory or resources that each thread wants to access. But because of the random nature of execution of each thread, there will be corruption of data when multiple threads try to read and write into the same memory space. One possible way to fix the problem is using locking mechanism like a mutex. POSIX provides a mutex called pthread_mutex_t just for this purpose. See POS00-C Avoid race conditions with multiple threads for more information.

Deadlock can happen when multiple threads each holds a lock the other needs and are waiting for each other to release the that resource. One way to fix the problem is to avoid circular wait by locking the mutex in a predefined order.

...

Based on runtime environment and the scheduler on the operating system, the following code will have different behaviors. Let's assume function thread1 and thread2 are called consecutively as in pthread_create is called from for thread2 right after pthread_create is called for thread1. If lucky, the code will run without any problems. In other times, the code will deadlock in which thread1 try to lock m1 while thread2 try to lock on m2 and the program will not progress.

...