Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/articles/cpp-tutorials/)
-   -   Program for shared memory in c++ (http://www.go4expert.com/articles/program-shared-memory-cpp-t8461/)

bashamsc 25Jan2008 11:36

Program for shared memory in c++
 
If two process are there and one shared memory is there. One wants to write the data and another wants to read the data to the shared memory.

I have written a program in which if process1 is writing to shared memory another will wait and vise varsa. To undersand these programs one should have the knowledge of shared memory in Linux.

I did for Linux platform not for others.

The programs are as follows:

process1.cpp

Code: Cpp

#include<iostream.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<unistd.h>

#define SHMSZ    1024

int write(int *b)
{
    char c;
    int shmid;
    key_t key;
    int *shm;
    char *s;

    /*
    * We'll name our shared memory segment
    * "5678".
    */

    key = 5678;

    /*
    * Create the segment.
    */

    if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
        cerr<<"shmget";
        exit(1);
    }

    /*
    * Now we attach the segment to our data space.
    */

    if ((shm = (int *)/*(char *)*/shmat(shmid, 0, 0)) == /*(char *)*/(int *) -1) {
        cerr<<"shmat";
        exit(1);
    }

    /*
    * Now put some things into the memory for the
    * other process to read.
    */

    // s = shm;
    int i;
    for (i=0; i<=1000; i++,shm++)
        *shm = i;

    *b=0;
    cout<<"write is complited"<<endl;
    cout<<*b<<endl;
    return(*b);
}
main()
{

    char c;
    int shmid;
    key_t key;
    static int *b;

    key = 5679;

    /*
    * Create the one bit  segment.
    */

    if ((shmid = shmget(key, 1, IPC_CREAT | 0666)) < 0) {
        cerr<<"shmget";
        exit(1);
    }

    /*
    * Now we attach the segment to our data space.
    */

    if ((b = ( int *)shmat(shmid, 0, 0)) == (int *) -1)
    {
        cerr<<"shmat";
        exit(1);

    }
    cout<<*b<<endl;
    while(1)
    {
        if(*b==1)
        {
            write(b);
        }
        else
            wait();
    }
}

I have created one bit shared memory for the logic.

process2.cpp

Code: Cpp

#include<iostream.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include<unistd.h>

#define SHMSZ    1024

int read(int *b)
{

    char c;
    int shmid;
    key_t key;
    int *shm;
    char *s;

    /*
    * We'll name our shared memory segment
    * "5678".
    */

    key = 5678;

    /*
    * Create the segment.
    */

    if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) {
        cerr<<"shmget";
        exit(1);
    }

    /*
    * Now we attach the segment to our data space.
    */

    if ((shm = (int *)shmat(shmid, 0, 0)) == (int *) -1) {
        cerr<<"shmat";
        exit(1);
    }


    /*now read what the server put in the memory.
    */

    int i;
    for (i=0; i<=1000; i++,shm++)
        cout<<*shm<<endl;
    cout<<"read is completed"<<endl;
    *b=1;
    cout<<"*b is "<<*b<<endl;
    return(*b);
}
main()
{

    char c;
    int shmid;
    key_t key;
    static int *b;

    key = 5679;

    /*
    * Create the one bit  segment.
    */

    if ((shmid = shmget(key, 1, IPC_CREAT | 0666)) < 0) {
        cerr<<"shmget";
        exit(1);
    }

    /*
    * Now we attach the segment to our data space.
    */

    if ((b = (int *)shmat(shmid, 0, 0)) == (int *) -1) {
        cerr<<"shmat";
        exit(1);

    }

    cout<<" *b is "<<*b<<endl;

    while(1)
    {
        if(*b==0)
        {
            read(b);
        }
        else
            wait();
    }
}

If u want to compile these programs then open two terminals and run process1.cpp and process2.cpp at a time. Then u will observe that if one is writing to the shared memory then another will be waiting vice vasa.

asadullah.ansari 25Jan2008 12:21

Re: program for shared memory in c++
 
Good One!!!

shabbir 3Feb2008 12:33

Re: program for shared memory in c++
 
Nominate this article for the month for January 2007

debleena_doll2002 6Feb2008 21:35

Re: Program for shared memory in c++
 
Can you tell me difference b/w semaphore and mutex practically

bashamsc 7Feb2008 16:42

Re: Program for shared memory in c++
 
Simple difference is that mutex is used in threads and semaphores are used in process.

Now i will explain what is a mutex and a semaphore.

Mutex

when two threads try to increment the same variable at the same time, they may leave the variable in an incorrect condition. This is true for every resource the threads share (memory variables, screen, modem etc.). The parts of the code that access the shared resource are called critical sections. To avoid using the same resource at the same time, a thread should perform some check to see whether there is another thread in the critical section. If there is no thread in the critical the thread may enter the critical section. Otherwise, it has to wait until the critical section is free again.

The mechanism that performs this check is called a mutex. A mutex has two states, that are usually referred to as unlocked and locked. An unlocked mutex indicates that the critical section is empty, and locked mutex indicates that there is some thread inside the critical section. A thread that wishes to access a resource checks the mutex associated with that resource. If the mutex is unlocked, it means there is no thread in the critical section, so the thread locks the mutex and enters the critical section. When the thread leaves the critical section it should unlock the mutex. If the mutex is locked, it means that there is another thread in the critical section, so the thread (that is trying to lock the mutex and enter) waits until the mutex becomes unlocked.

How mutex work. (and how they don't)

There are two operations defined on a mutex (beside initializing and destroying). The first is an operation that checks the state of the mutex, and then it locks the mutex if it is unlocked, or waits until it becomes unlocked. This operation is usually called lock. The second operation unlocks the mutex, and it usually is called unlock.

The first question that should arise is what happens when two threads call lock at the same time. Seemingly, they could ruin the mutex. However, notice that the operating system performs the lock (it is a function of the OS), and we know that the operating system is the one that decides when to schedule a new thread. Combining this information we get an elegant solution. When executing the lock function the operating system does not allow rescheduling. More specifically, the code of lock disables interrupts. This way two lock functions cannot ruin the mutex.

The second question that should arise is how the Os checks that a locked mutex was unlocked. Afterall, checking every some period of time is very not efficient. The answer is, it doesn't! The OS does not check whether a mutex is unlocked every some period of time! Every mutex has a list of threads that are waiting for it to unlock. When a thread discovers a mutex is locked, it adds itself to the waiting list. When the mutex is unlocked, the OS chooses one of the threads in the waiting list of that mutex, and wakes this thread. The thread then will try to lock the mutex again.

Syntax in Linux

Defining and initializing a mutex

A mutex is defined with the type pthread_mutex_t, and it needs to be assigned the initial value: "PTHREAD_MUTEX_INITIALIZER";

Locking a mutex

A mutex is locked with the function: pthread_mutex_lock(pthread_mutex_t *mutex)). This function gets a pointer to the mutex it is trying to lock. The function returns when the mutex is locked, or if an error occurred. (a locked mutex is not an error, if a mutex is locked the function waits until it is unlocked).

Unlocking a mutex

A mutex is unlocked with the function: pthread_mutex_unlock(pthread_mutex_t *mutex)).

Semaphore

A semaphore is an extension of a mutex. A mutex allows one thread inside the critical section, a semaphore allows n threads in a critical section (when the number n is given as a parameter on the initialization). A semaphore is useful when a resource has more than one instance, and a mutex can be implemented by initializing a semaphore with the value 1.

There are two operations defined on a semaphore (beside initializing and destroying). The first is an operation that checks the value of the semaphore, and then it decreases it by 1 if it is positive, or waits until it becomes positive. This operation is usually called wait or decrease. The second operation increases the value of the semaphore, and it usually is called post or increase.

Syntax in Linux

Defining and initializing a semaphore

A semaphore is defined with the type sem_t, and it need to be initialized with the function sem_init.

Waiting on a semaphore

The value of a semaphore is decreased with the function: sem_wait. This function gets a pointer to the semaphore it is trying to decrease. The function returns when the semaphore's value is decreased, or if an error occurred. (a semaphore with value 0 is not an error, if a semaphore is 0 the function waits until it is positive).



If u want an ex. program i can give u.

But to understand the program u have to know the what is a thread and what is a process.

debleena_doll2002 7Feb2008 17:09

Re: Program for shared memory in c++
 
Why you have copied from other sites. You know this is Crime to copy article/message of others. So please i am saying straight forward for allone Dont copy and paste of other article. Read that article and express yourself.

You have taken this article from
http://www.math.tau.ac.il/~hayim/cou...5/lecture.html

debleena_doll2002 7Feb2008 17:17

Re: Program for shared memory in c++
 
Your starting thread is also copied from

http://www.mec.ac.in/resources/tutor...xc/node27.html

I am surprised this article is nominated for month of Jan2008

debleena_doll2002 7Feb2008 17:18

Re: Program for shared memory in c++
 
Please I am requesting to all of "This is totally CRIME". So i request to moderator or responsible person to see it.

bashamsc 8Feb2008 12:05

Re: Program for shared memory in c++
 
sorry for that.

I copied mutex and semaphore to explain u.

I thought of giving link.

If u want to explain clearly i will explain in my words.

The first thread was not copied.

check my program carefully and compare with which u have given the link.

Why i am telling confidently because i have developed it and i am working on supercomputer
namely Flosolver. This super computer is the India's first parallel supercomputer.

If u still believe i am ready to remove this thread.

debleena_doll2002 8Feb2008 15:26

Re: Program for shared memory in c++
 
Okay No Probs at all... But If anyone copied from other site then he has to give the links also so that writer of that content/article can'nt rise any issues.

You can get a lot of cases against rule in USA regarding this. So i am telling not to you but this message is to all of people in this forum.

I am sorry if any thing said to u regarding your own article.


All times are GMT +5.5. The time now is 05:50.