epoll/select for mutexes/semaphores
When you have a set of pipes/sockets waiting for read/write, epoll() or select() can be used to wait on all of them until at least one of them are ready for read/write.
Is there anything similar for threads/pthreads? The closest I've got on doing this is making a sleeping thread by blocking on lock() for mutexes. However, this costs a thread for each lock.
I also thought about using pipes i开发者_如何转开发nstead of these locks, but it also seems inefficient, and the pipe count seems to be limited to around 500 pipes (at least it's a little higher than threads).
So yeah, are there better solutions than using threads on waiting for mutexes to unlock?
eventfd
might be of use for you. They should work the same way as your pipes but the overhead is much much smaller.
If you're hitting the 1024 open files limit, you can increase it to as much as you want using ulimit. But, if you have many locks, there should some more intelligent use of the eventfd's.
Here's some more info: http://man7.org/linux/man-pages/man2/eventfd.2.html
I don't know of any such methods, but you might want to rethink the design leading to such a problem. If you are trying to wait for the availability of a number of mutexes in unspecified order (probably locking some of them in the process), the Dining Philosophers problem seems very likely to lurk just around the corner.
If that's not the problem, a condition variable is probably the way to go.
maybe you are looking for conditional variables. See man pages for pthread_cond_init, pthread_cond_wait and pthread_cond_signal.
If one thread call pthread_cond_wait(cond) it waits until the second thread calls pthread_cond_signal(cond)
精彩评论