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

How to use Mutex in C

Discussion in 'C' started by imported_dharmdeep, Nov 11, 2006.

  1. imported_dharmdeep

    imported_dharmdeep New Member

    Joined:
    Nov 11, 2006
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi Friends,

    I have made a client server application in which multiple clients can interact with server. but when two or more clients get connected at the same time then memory error occurs. So I think i have to use some synchronization tecnique to get things working properly. i thought of using mutex. Can anybody help me with some sample code as how to use mutex in C under windows.
     
  2. Bill Pursell

    Bill Pursell New Member

    Joined:
    Nov 29, 2006
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    I can't help with your windows specific question, but the following works on OS X. Probably the only thing you'll need to change, if anything, is the names of the header files.
    Code:
    #include <semaphore.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <sys/types.h>
    #include <unistd.h>
    
    int
    main(int argc, char **argv)
    {
            sem_t *sem;
            const char *name;
    
            name = (argc > 1) ? argv[1] : "foo";
            sem = sem_open(name, O_CREAT, 0777, 1);
    
            if (sem == (sem_t *)SEM_FAILED) {
                    perror(name);
                    exit(EXIT_FAILURE);
            }
    
            fprintf(stderr, "%d waits...", getpid());
    
            if (sem_wait(sem) == -1) {
                    perror(name);
                    exit(EXIT_FAILURE);
            }
    
            fprintf(stderr, "Got %s\n", name);
            sleep(5);
            sem_post(sem);
    
            return EXIT_SUCCESS;
    }
     
  3. NewsBot

    NewsBot New Member

    Joined:
    Dec 2, 2008
    Messages:
    1,267
    Likes Received:
    1
    Trophy Points:
    0
    Good sample I must say.
     

Share This Page