Anycorn
Anycorn

Reputation: 51445

pthreads mutex number and performance

Upvotes: 1

Views: 2861

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215193

POSIX allows mutexes to be implemented as a system-level resource, but such an implementation would be considered extremely poor quality and I can't imagine anyone using it. In reality, on modern implementations (think Linux), the number of mutexes you can have is limited only by the virtual address space. (Actually you can have even more, up to the total size of physical memory/swap plus filesystem size, if you use mmap and munmap to map them in and out as needed.)

As for performance, on 32-bit glibc systems, unlocking robust mutexes is an O(n) operation, where n is the number of robust mutexes currently locked. This is due to using a singly-linked list where a doubly-linked one is needed; they ran out of space in their pthread_mutex_t structure to fit both pointers. This issue only applies for robust mutexes, which are rarely used in practice, and only on 32-bit Linux/glibc. For all other mutex types, the number of mutexes has no impact on performance. The number of currently-contended-for mutexes, however, does have some impact on performance, but it's a complicated subject beyond the scope of a simple answer.

Upvotes: 3

Employed Russian
Employed Russian

Reputation: 213386

Several answers:

  1. You are asking the wrong question. If you need more than a 1000 or so mutexes, you are likely doing something wrong.
  2. As many as you need. Non-process-shared mutex does not usually consume any resources except RAM.
  3. Having many unused mutexes degrades performance in exactly the same way as having many integers; that is, not at all (assuming sufficient RAM).

Upvotes: 1

Related Questions