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.

shabbir 8Feb2008 21:55

Re: Program for shared memory in c++
 
debleena_doll2002, thanks for pointing that out but the link you provided does not have the complete code that is there in the article in the forum here ( or at least it does not open up perfectly for me ).

coderzone 9Feb2008 13:09

Re: Program for shared memory in c++
 
I think it should be nominated

debleena_doll2002 11Feb2008 10:45

Re: Program for shared memory in c++
 
Dear Obaid!!! Here matter is not for nomited or not. Here matter is for voilating some IT rules comming under section(........i dont know which section).

coderzone 11Feb2008 11:16

Re: Program for shared memory in c++
 
Quote:

Originally Posted by debleena_doll2002
Dear Obaid!!! Here matter is not for nomited or not. Here matter is for voilating some IT rules comming under section(........i dont know which section).

I was just letting Admin and mod know that there is nothing wrong in the article as far as my understanding of the matter goes and so it can be nominated. Probably the short form I used did not say everything.

debleena_doll2002 13Feb2008 13:50

Re: Program for shared memory in c++
 
Quote:

Originally Posted by Obaid
I think it should be nominated

By your above statement Who will understand that you are only talking to admin.

imrantechi 13Feb2008 14:03

Re: Program for shared memory in c++
 
i m not so well versed with linux, so can you provide a little more explanation ,

so that even people like us also can understand.

imrantechi 13Feb2008 14:08

Re: Program for shared memory in c++
 
Quote:

Originally Posted by debleena_doll2002
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

i found your article has been nominated for this month,

but you have copied from other sites ,this means your article should not have been nominated.

bashamsc 13Feb2008 15:26

Re: Program for shared memory in c++
 
Quote:

Originally Posted by imrantechi
i found your article has been nominated for this month,

but you have copied from other sites ,this means your article should not have been nominated.

Hi,

I have not copied any article.

The program that i have posted is developed by me.

If u have any doubts u can compare and run my program in Linux.

As u can see in mutex and semaphore i did that to give clear picture for explaination. I thought of giving link to her.

My thought to help her.Nothing than that.

asadullah.ansari 13Feb2008 15:33

Re: Program for shared memory in c++
 
Quote:

Originally Posted by bashamsc
Hi,

I have not copied any article.

The program that i have posted is developed by me.

If u have any doubts u can compare and run my program in Linux.

As u can see in mutex and semaphore i did that to give clear picture for explaination. I thought of giving link to her.

My thought to help her.Nothing than that.


whatever in article it was not copied . Okay No Issues at all regarding this article.

Second time he posted that was not article just he is explaining to her.

So why you are making nonsense. At all No issue should be regarding this.
Raising unneccessary please disscuss about technical and some meaningfull matters so that we can develope us and as well forum.

imrantechi 13Feb2008 15:49

Re: Program for shared memory in c++
 
Quote:

Originally Posted by bashamsc
Hi,

I have not copied any article.

The program that i have posted is developed by me.

If u have any doubts u can compare and run my program in Linux.

As u can see in mutex and semaphore i did that to give clear picture for explaination. I thought of giving link to her.

My thought to help her.Nothing than that.

i have gone through the link and found that the program is your 's
i regret for the issue

shabbir 13Feb2008 17:14

Re: Program for shared memory in c++
 
Quote:

Originally Posted by imrantechi
i have gone through the link and found that the program is your 's
i regret for the issue

Even I did the same and so we would like to make sure we conclude that its an original contribution.

bashamsc 13Feb2008 19:26

Re: Program for shared memory in c++
 
Quote:

Originally Posted by imrantechi
i m not so well versed with linux, so can you provide a little more explanation ,

so that even people like us also can understand.

See to understand the program first u need to have an idea of shared memory.

Shared memory comes under Inter-Process Communication.

Shared memory is the fastest of all IPC.

Shared memory comes under System V IPC.

SHARED MEMORY:

Shared memory is one of the three System V IPC.

It allows two unrelated processes to access the same logical memory.

Shared memory is a very efficient way of transferring data between two running processes.


In the program i have used these functions.

shmget and shmat for shared memory.

shmget is used to create shared memory.

shmat is used to attach the shared memory to the address space of the process.

When we come to the program,i have created two process i.e process-1 and process-2.

process-1 and process-2 uses same memory i.e shared memory.

I have created a single bit shared memory to control the two process not to access the shared memory at a time.

When process-1 uses the shared memory then process-2 waits until process-1 completes its work and wise versa .

Run the two process at a time (i.e in two terminals ) and u will observe that When process-1 uses the shared memory then process-2 waits until process-1 completes its work and wise versa .

imrantechi 13Feb2008 19:31

Re: Program for shared memory in c++
 
Okay!!! Thanks man...

debleena_doll2002 13Feb2008 19:40

Re: Program for shared memory in c++
 
Leave it bashamsc !!! your effort is really apprecited. Now please dont make issue more. That article should be nominated!!! Finallllll

shabbir 19Feb2008 12:45

Re: Program for shared memory in c++
 
Voting for article of the month for January 2008

lead.smart34 26Feb2008 18:21

Re: Program for shared memory in c++
 
its complex

crazytolearn57 26Feb2008 18:36

Re: Program for shared memory in c++
 
what is this problem of copy

rlearntowin1 27Feb2008 09:26

Re: Program for shared memory in c++
 
good one

bashamsc 27Feb2008 16:30

Re: Program for shared memory in c++
 
see this blog www.sharedmemoryprogram.blogspot.com

shabbir 28Feb2008 17:32

Re: Program for shared memory in c++
 
Winner of the month for January 2008

asadullah.ansari 28Feb2008 19:20

Re: Program for shared memory in c++
 
Congrates man!!!

aisha.ansari84 5Mar2008 18:16

Re: Program for shared memory in c++
 
congrats you won

sorabh284 25Mar2009 21:57

Re: Program for shared memory in c++
 
when we pass object as argument to a function, then whether constructor or destructor are called or not.

Mufasa 28Jul2010 20:39

Re: Program for shared memory in c++
 
Hi @all,

ok this thread is a bit old already.... but I'm working on quite the same issue now so I thought I refresh this instead of starting a new...

1st: Big thanks to bashamsc for this great code!!

Now what I am trying to do for a while now.... ( without any success until now :( ) is to access this SHM with PHP. So I have a shared-memory created with C++ and I want to read and change the data inside with PHP and read with C++ again and so on...... U know what I mean? I know a bit difficult to explain....

Allright, I know how to create a shm with php and write data inside..... but how the h*** can I access this C++ created shm??

Appreciate every help or suggestion.

Thanks in advance & regards from Germany :-)

banty_raju123 29Jul2010 10:39

Re: Program for shared memory in c++
 
ur information is very useful for me thankx


All times are GMT +5.5. The time now is 20:11.