How to synchronise two processes using a semaphore

343 views Asked by At

I have been asked to synchronize 2 processes that share an integer in shared memory. The synchronization is to be done with a semaphore.

The first process start incrementing the integer from 2 in steps of 2 up 10, when it should block because the integer is 0 mod 5, permitting the second process to continue incrementing the same integer but with 3 this time, and also stop when the integer is 0 mod 5; then its loop all the way. Until 100

I wrote this code and I was unsure whether I could write V(s) and P(s) successfully.

First process

#define keys 100
#define key 200

main()
{
    int s, idm, *n = 0;

    idm = shmget(key, sizeof(int), ipc - creat | 0666);
    creat - sem(keys);
    init - sem(idm, 0, 0);
    n = (int *)shmat(idm, 0, 0);
    while (*n < 100)
    {
        *n += 2;
        printf(% d, *n);
        if (*n % 5 == 0)
        {
            V(s);
            P(s);
        }
        shmdt(n);
    }  

Second process

#define keys 100
#define key 200

main()
{
    int s, idm, *n = 0;
    idm = shmget(key, sizeof(int), ipc - EXCL | 0666);
    creat - sem(keys);
    init - sem(idm, 0, 0);
    n = (int *)shmat(idm, 0, 0);
    P(s);
    while (*n < 100)
    {
        *n += 3;
        printf(% d, *n);
        if (*n % 5 == 0)
        {
            V(s);
            P(s);
        }
        shmdt(n);
        smctl(idm, IPC - RMID, 0);
    }
0

There are 0 answers