how to set the priority to get the mutex in C/c++

2019-04-28 04:10发布

问题:

I have 3 process (equal priority)

  1. P1
  2. P2
  3. P3(timer)

priority to get the mutex is as follows: P1(1 priority), P2(2 priority), P3(timer)(3 priority)

If suppose p3 comes and get the mutex then p2 comes and wait for mutex after that p1 comes and it also wait for mutex

if p3 release mutex then p1 should get the mutex not p2.

How to perform this in C or C++.

Note : all processes are running inside threads having same priority.

OS - windows Xp

回答1:

Since the threads have equal priority, which thread gets the lock will be rather arbitrary. It appears you want to wait on a condition variable rather than using a simple mutex. You will still have a mutex; condition 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 interface (C-style): https://computing.llnl.gov/tutorials/pthreads/#ConVarSignal

An important question you need to ask yourself: With all of this waiting and synchronization, are you buying anything? The purpose of using threads is to let some things run in parallel. If that is not happening, you have a multithreaded application that runs slower than if the application didn't use threads at all.



回答2:

SetThreadPriority(
   HANDLE hThread,
   int nPriority
);

this function will set the priority of your threads .... the HANDLE value you will get while creating thread.. like

:HANDLE hf=_beginthred(abc,0,NULL) 


回答3:

Making lock acquisition based on priority is a recipe for deadlocks. Locking should always be done in predictable order, or you will have the classical (A,B), (B,A) deadlock possibility.

You will instead want to work with a priority queue and let the lock itself be kernel managed. You could of course use a semaphore instead of a mutex to let the kernel know how many waiting threads to awake on queued items. However, you'll still want to lock the queue itself when accessing it



回答4:

When you wait on a mutex, the process's thread is added in the mutex waiting queue (a linked list) and your only chance would be to have the possibility to change the selection behavior in the queue. Maybe Windows offers this possibility or maybe the queue is by default sorted by priority (which is the most likely).

The fact that your processes have the same priority is not a problem since a thread timeslice will be function of the process and thread priority.