码迷,mamicode.com
首页 > 系统相关 > 详细

Linux IPC (Semaphore)

时间:2015-08-07 19:08:45      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

/*
 * This demo shows how to use semaphore between threads.
 *
 */

#include <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>

/*
 * Global var
 */
int number;
sem_t sem_id;

void* thread_one_fun(void *arg)
{
   sem_wait(&sem_id);

   printf("thread_one have the semaphore\n");
   number++;
   printf("number = %d\n",number);

   sem_post(&sem_id);
}


void* thread_two_fun(void *arg)
{
    sem_wait(&sem_id);
    printf("thread_two have the semaphore \n");
    number--;
    printf("number = %d\n",number);

    sem_post(&sem_id);
}


int main(int argc, char **argv)
{
    number = 1;
    pthread_t id1, id2;

    sem_init(&sem_id, 0, 1);

    pthread_create(&id1,NULL,thread_one_fun, NULL);
    pthread_create(&id2,NULL,thread_two_fun, NULL);

    pthread_join(id1,NULL);
    pthread_join(id2,NULL);

    printf("main...\n");

    exit(0);
}


 

 

/*
 * This demo shows how to use semaphore between processes.
 */

#include <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>

int main(int argc, char **argv)
{
    int fd, i,count=0,nloop=10,zero=0,*ptr;
    sem_t mutex;

    /*
     * open a file and map it into memory
     */
    fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU);
    write(fd,&zero,sizeof(int));
    ptr = mmap( NULL,sizeof(int),PROT_READ |
            PROT_WRITE,MAP_SHARED,fd,0 );
    close(fd);

    /* create, initialize semaphore */
    if( sem_init(&mutex,1,1) < 0)
    {
        perror("semaphore initilization");
        exit(0);
    }

    if (fork() == 0)
    { /* child process*/
        for (i = 0; i < nloop; i++)
        {
            sem_wait(&mutex);
            printf("child: %d\n", (*ptr)++);
            sem_post(&mutex);
        }
        exit(0);
   }

    /* back to parent process */
    for (i = 0; i < nloop; i++)
    {
        sem_wait(&mutex);
        printf("parent: %d\n", (*ptr)++);
        sem_post(&mutex);
    }

    exit(0);
}


 

Linux IPC (Semaphore)

标签:

原文地址:http://www.cnblogs.com/qingxueyunfeng/p/4711213.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!