Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c/c++ maximum number of mutexes allowed in Linux

I've been searching trying to find out what is the maximum number of mutexes in Linux for a c/c++ process without success. Also, is there a way to modify this number. The book I'm reading mentions how to find the max number of threads allowed in Linux and how to modify this number but no mention of mutexes.

like image 787
WhatIf Avatar asked Sep 11 '15 19:09

WhatIf


1 Answers

Check this pthread_mutex_init.

Why No Limits are Defined

Defining symbols for the maximum number of mutexes and condition variables was considered but rejected because the number of these objects may change dynamically. Furthermore, many implementations place these objects into application memory; thus, there is no explicit maximum.


EDIT: In the comments you asked about the costs a mutex may have other than memory. Well, I don't know, but I found some interesting material about that:

This article on How does a Mutex Work says this about the costs:

The Costs

There are a few points of interest when it comes to the cost of a mutex. The first, and very vital point, is waiting time. Your threads should spend only a fraction of their time waiting on mutexes. If they are waiting too often then you are losing concurrency. In a worst case scenario many threads always trying to lock the same mutex may result in performance worse than a single thread serving all requests. This really isn’t a cost of the mutex itself, but a serious concern with concurrent programming.

The overhead costs of a mutex relate to the test-and-set operation and the system call that implements a mutex. The test-and-set is likely very low cost; being essential to concurrent processing the CPUs have good reason to make it efficient. We’ve kind of omitted another important instruction however: the fence. This is used in all high-level mutexes and may have a higher cost than the test-and-set operation. More costlier than even that however is the system call. Not only do you suffer the context switch overhead of the system call, the kernel now spends some time in its scheduling code.

So I'm guessing the costs they talk about on the EAGAIN error involves either the CPU or internal kernel structures. Maybe both. Maybe some kernel error... I honestly don't know.


StackOverflow resources

I picked some SO Q&A that might interest you. Good reading!

  • How efficient is locking an unlocked mutex? What is the cost of a mutex?
  • How pthread_mutex_lock is implemented
  • How do mutexes really work?
  • When should we use mutex and when should we use semaphore
like image 192
Enzo Ferber Avatar answered Oct 04 '22 23:10

Enzo Ferber