user6830335
user6830335

Reputation:

Mutual excluding and process synchronization; C++

I have a problem with 2 processes synchronization. I have 3 X processes and 5 Y processes. Also I have 2 resources - A and B.

Resource'A' may be used by max 3 proceses at the same time, and by accessing to resource 'B' mutual excluding is necessary.

process X and Y:

void processX()
{
    while (1)
    {
        AccessToResource(B);

        AccessToResource(A);
    }
}

void processY()
{
    while (1)
    {
        AccessToResource(A);

        AccessToResource(B);
    }
}

How can I do that using Semaphores, Mutexes, Events, the shortest way?

For now I have

CSemaphore sem(1,5,L"semaph");

and using it by sem.Lock() and sem.Unlock() before and after accessing to resource but it's not quite good.

Upvotes: 0

Views: 76

Answers (1)

Yuriy Ivaskevych
Yuriy Ivaskevych

Reputation: 966

Resource'A' may be used by max 3 proceses

Counting semaphore would be suitable here (see wiki). It works as folows:

You have some counter (thus the name) initialized with 0. Every time some process owns resource A it increases that semaphore by 1. If count hits 3 in your case that'll mean there are already 3 processes using resource 'A'. After process finished using resource 'A' it decreases that counter (semafore) by 1, thus allowing other processes to use that resource.

by accessing to resource 'B' mutual excluding is necessary

Here a suitable solution would be a mutex (or binary semaphore). They both work almost the same - the difference that mutex has an emphasis on owing the resource.

Upvotes: 1

Related Questions