1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Program for shared memory in c++

Discussion in 'C++' started by bashamsc, Jan 25, 2008.

  1. bashamsc

    bashamsc New Member

    Joined:
    May 22, 2007
    Messages:
    51
    Likes Received:
    7
    Trophy Points:
    0
    Location:
    chennai
    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:
    #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:
    #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.
     
    Last edited: Feb 26, 2008
  2. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
  4. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
    Can you tell me difference b/w semaphore and mutex practically
     
  5. bashamsc

    bashamsc New Member

    Joined:
    May 22, 2007
    Messages:
    51
    Likes Received:
    7
    Trophy Points:
    0
    Location:
    chennai
    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.
     
    shabbir likes this.
  6. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
  7. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
  8. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
    Please I am requesting to all of "This is totally CRIME". So i request to moderator or responsible person to see it.
     
  9. bashamsc

    bashamsc New Member

    Joined:
    May 22, 2007
    Messages:
    51
    Likes Received:
    7
    Trophy Points:
    0
    Location:
    chennai
    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.
     
  10. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
    Last edited: Feb 8, 2008
  11. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,287
    Likes Received:
    364
    Trophy Points:
    83
    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 likes this.
  12. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    734
    Likes Received:
    37
    Trophy Points:
    0
    I think it should be nominated
     
  13. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
    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).
     
  14. coderzone

    coderzone Super Moderator

    Joined:
    Jul 25, 2004
    Messages:
    734
    Likes Received:
    37
    Trophy Points:
    0
    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.
     
  15. debleena_doll2002

    debleena_doll2002 New Member

    Joined:
    Feb 5, 2008
    Messages:
    119
    Likes Received:
    0
    Trophy Points:
    0
    By your above statement Who will understand that you are only talking to admin.
     
  16. imrantechi

    imrantechi New Member

    Joined:
    Feb 12, 2008
    Messages:
    116
    Likes Received:
    4
    Trophy Points:
    0
    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.
     
  17. imrantechi

    imrantechi New Member

    Joined:
    Feb 12, 2008
    Messages:
    116
    Likes Received:
    4
    Trophy Points:
    0
    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.
     
  18. bashamsc

    bashamsc New Member

    Joined:
    May 22, 2007
    Messages:
    51
    Likes Received:
    7
    Trophy Points:
    0
    Location:
    chennai
    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.
     
  19. asadullah.ansari

    asadullah.ansari TechCake

    Joined:
    Jan 9, 2008
    Messages:
    356
    Likes Received:
    14
    Trophy Points:
    0
    Occupation:
    Developer
    Location:
    NOIDA

    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.
     
  20. imrantechi

    imrantechi New Member

    Joined:
    Feb 12, 2008
    Messages:
    116
    Likes Received:
    4
    Trophy Points:
    0
    i have gone through the link and found that the program is your 's
    i regret for the issue
     

Share This Page