How to allow certain threads to have priority in locking a mutex use PTHREADS

前端 未结 6 1234
天命终不由人
天命终不由人 2020-12-15 23:32

Assume that the following code is being executed by 10 threads.

pthread_mutex_lock(&lock)
Some trivial code
pthread_mutex_unlock(&lock)
6条回答
  •  不思量自难忘°
    2020-12-16 00:08

    As I understand it, the only way you can truly guarantee this would be to write a lock that works like that yourself. However @xryl669's answer that suggests using thread priority and priority inheritance is certainly worthy of consideration if it works for your use case.

    To implement it yourself, you will need condition variables and counts of the number of waiting low / high priority threads.

    In terms of the concepts and APIs you'll need, it is relatively similar to implementing a read/write lock (but the semantics you need are completely different, obviously - but if you understood how the r/w lock is working, you'll understand how to implement what you want).

    You can see an implementation of a read write lock here:

    http://ptgmedia.pearsoncmg.com/images/0201633922/sourcecode/rwlock.c

    In the lower priority threads, you'd need to wait for high priority threads to finish, in the same way readers wait for writers to finish.

    (The book the above code is taken from it also a great posix threads book btw, http://www.informit.com/store/product.aspx?isbn=0201633922 )

提交回复
热议问题