How to set priority for getting mutex in C / C ++

I have 3 processes (equal priority)

  • P1
  • P2
  • P3 (timer)

Mutex priority: P1(1 priority), P2(2 priority), P3(timer)(3 priority)

If we assume that p3 comes and receives the mutex, then p2 comes and waits for the mutex, after that p1 comes, and also waits for mutex

if p3 is a mutex release, then p1 should get a mutex not p2 .

How to do this in C or C ++.

Note: all processes run inside threads with the same priority.

OS - Xp windows

+6
source share
4 answers

Since threads have the same priority, a thread that receives a lock will be pretty arbitrary. It seems you want to wait for the condition variable, rather than using a simple mutex. You will still have a mutex; state variables are a concept on top of mutexes. Another possibility is to use synchronization barriers.

EDIT: An example of using condition variables using the pthreads (C-style) interface: https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal

The important question you need to ask yourself is: do you buy anything with all this expectation and synchronization? The purpose of using threads is to allow some things to work in parallel. If this does not happen, your multi-threaded application runs slower than if the application does not use threads at all.

+2
source
 SetThreadPriority( HANDLE hThread, int nPriority ); 

this function will set the priority of your threads .... the HANDLE value that you get when creating the thread .. for example

 :HANDLE hf=_beginthred(abc,0,NULL) 
+2
source

Creating a priority-based lock is a recipe for deadlocks . The lock should always be performed in a predictable order or you will have the classic ability to lock (A, B), (B, A).

Instead, you want to work with the priority queue and let the lock itself control the kernel. Of course, you can use a semaphore instead of a mutex so that the kernel can find out how many waiting threads are awakening in queued items. However, you still want to block the queue when accessing it

+1
source

When you wait for a mutex, the process thread is added to the mutex wait queue (linked list), and your only chance is to be able to change the selection behavior in the queue. Perhaps Windows offers this feature, or maybe the default queue is sorted by priority (which is most likely).

The fact that your processes have the same priority is not a problem, as the temporary thread flow will work with the thread priority and .

0
source

Source: https://habr.com/ru/post/889364/


All Articles