Linux下进程的同步相互排斥实例——生产者消费者
linux下的同步和相互排斥
Linux
sync_mutex
看的更舒服点的版本号= =
https://github.com/Svtter/MyBlog/blob/master/Linux/pthread/Linux_producer_consumer.md
Semaphore.h
一份好文档,胜读十年书
本文參考了诸多资料,百度百科。cplusplus等
首先介绍一个头文件
#include <semaphore.h>
这里面包括了大多数的所须要使用的信号量.
包括:
int sem_init(sem_t *sem, int pshared, unsigned int value)
用于初始化信号量。
value代表信号量的初始值,
pshare代表信号量是进程内的线程共享。还是进程间共享。
对于Linux而言,就是子进程共享和父进程共享——Linux中不存在线程的问题。Linux中的线程。进程均为进程。仅仅是看进程组。子进程父进程而已。对于进程关系。能够使用
pstree
查看。
返回0时成功。返回-1时失败。而且设置errno
使用perror输出错误信息:
- EINVAL
value 超过 `SEM_VALUE_MAX`
- ENOSYS
pshared 非零。但系统还没有支持进程共享的信号量。
int sem_post(sem_t *sem)
这个函数相当于V操作,是一个"原子操作"——即是不会被打断(中断)的。并行计算中会出现的两个线
程同一时候对一个变量相加导致变量的值仅产生了一次变化在此处是不成立的。
返回0时成功,返回-1时失败, 而且设置errno:- EINVAL
sem 不是一个有效的信号量。 - EOVERFLOW
信号量同意的最大值将要被超过。
- EINVAL
int sem_wait(sem_t *sem)
这个函数相当于P操作,也是一个"原子操作"。等待对变量-1,假设不能对变量-1,则进入等待队列
int sem_trywait(sem_t *sem)
假设变量不能-1(即sem_t
为0),则不会进入等待队列,直接返回错误代码。int sem_timedwait(sem_t *sem)
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
- return 0 (success), return -1 (failure) and set errno:
- EINTR
The call was interrupted by a signal handler; see signal(7).
//调用被信号处理中断 - EINVAL sem is not a valid semaphore.
//sem不是有效的信号量
The following additional error can occur for sem_trywait():
//以下的错误是sem_trywait()可能发生的: - EAGAIN The operation could not be performed without blocking (i.e., the
semaphore currently has the value zero).
//除了锁定无法进行别的操作(如信号量当前是0值).
The following additional errors can occur for sem_timedwait():
//以下的错误是sem_timedwait()可能发生的: - EINVAL The value of abs_timeout.tv_nsecs is less than 0, or greater than or
equal to 1000 million.
//abs_timeout.tv_nsecs 的值比0小或者大于等于1000毫秒(译者注:纳秒的值不能比0小,不能比1秒大) - ETIMEDOUT
The call timed out before the semaphore could be locked.
//在信号量锁定之前就超时了 - 注意
对这些函数,信号处理程序总是会中断堵塞,无论是否使用了sigaction(2)的SA_RESTART标志位.
- EINTR
- return 0 (success), return -1 (failure) and set errno:
/*=============================================================================
#
# Author: svtter - svtter@qq.com
#
# QQ : 57180160
#
# Last modified: 2014-10-03 20:35
#
# Filename: producer_consumer.cc
#
# Description:
#
=============================================================================*/
#include <cstdio>
#include <unistd.h>
#include <semaphore.h>
#include <pthread.h>
#include <sys/types.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
#define N 5
#define item int
// P/V操作
void P(sem_t* sem)
{
if(sem_wait(sem))
perror("P error!");
}
void V(sem_t* sem)
{
if(sem_post(sem))
perror("V error!");
}
sem_t mutex;
sem_t full;
sem_t empty;
item buffer[N];
int i = 0, j = -1;
void init_sem()
{
sem_init(&mutex, 0, 1);
sem_init(&full, 0, 0);
sem_init(&empty, 0, N);
}
void* producer(void *arg)
{
int product;
while(1)
{
//生成随机数字
product = rand()%100;
// cout << "producer running..." << endl;
P(&empty);
P(&mutex);
buffer[i] = product;
printf("producer produced %d @ %d pos\n",
product, i);
i=(i+1)%N;
V(&mutex);
V(&full);
sleep(1);
}
}
void* consumer(void *arg)
{
int product, temp;
while(1)
{
// cout << "consumer running..." << endl;
P(&full);
P(&mutex);
j = (j+1)%N;
product = buffer[j];
V(&mutex);
V(&empty);
printf("Consumer consumed %d @ %d pos\n",
product, j);
sleep(3);
}
}
int main()
{
//random num
srand(time(NULL));
init_sem();
int error;
pthread_t producer_t, consumer_t;
error = pthread_create(&producer_t, NULL, producer, NULL);
if(error != 0)
printf("error in create producer.\n");
else
printf("create producer success!\n");
pthread_create(&consumer_t, NULL, consumer, NULL);
if(error != 0)
printf("error in create consumer.\n");
else
printf("create consumer success!\n");
pthread_join(producer_t, NULL);
pthread_join(consumer_t, NULL);
return 0;
}
Linux下进程的同步相互排斥实例——生产者消费者的更多相关文章
- linux系统编程:线程同步-相互排斥量(mutex)
线程同步-相互排斥量(mutex) 线程同步 多个线程同一时候訪问共享数据时可能会冲突,于是须要实现线程同步. 一个线程冲突的演示样例 #include <stdio.h> #includ ...
- Linux下进程通信的八种方法
Linux下进程通信的八种方法:管道(pipe),命名管道(FIFO),内存映射(mapped memeory),消息队列(message queue),共享内存(shared memory),信号量 ...
- 【网络编程基础】Linux下进程通信方式(共享内存,管道,消息队列,Socket)
在网络课程中,有讲到Socket编程,对于tcp讲解的环节,为了加深理解,自己写了Linux下进程Socket通信,在学习的过程中,又接触到了其它的几种方式.记录一下. 管道通信(匿名,有名) 管道通 ...
- 《linux下进程的创建,执行,监控和终止》
<linux下进程的创建,执行,监控和终止> http://blog.csdn.net/miss_acha/article/details/43671047 http://blog.csd ...
- 【Linux】Linux下进程间的通信方式
本文内容: 1.进程通信的目的 2.介绍Linux下进程间的4种通信方式:管道,消息队列,共享内存,信号量 ps:套接字也可以用于进程间的通信,不过是不同物理机器上的进程通信,本章讨论是是同一台物理机 ...
- linux 下进程通讯详解
linux 下进程通讯方法主要有以下六种: 1.管道 2.信号 3.共享内存 4.消息队列 5.信号量 6.socket
- 【Linux下进程机制】从一道面试题谈linux下fork的运行机制
今天一位朋友去一个不错的外企面试linux开发职位,面试官出了一个如下的题目: 给出如下C程序,在linux下使用gcc编译: #include "stdio.h" #includ ...
- Linux下进程的建立
Linux下进程的建立 我们都知道,进程就是正在执行的程序.而在Linux中,可以使用一个进程来创建另外一个进程.这样的话,Linux的进程的组织结构其实有点像Linux目录树,是个层次结构的,可以使 ...
- Linux下进程间管道通信小作业
在进行这次作业之前,我们先来看看什么是管道吧! 管道是Linux中很重要的一种通信方式,是把一个程序的输出直接连接到另一个程序的输入,常说的管道多是指无名管道,无名管道只能用于具有亲缘关系的进程之间, ...
随机推荐
- java 中的Exception RuntimeException 区别
在java的异常类体系中: 1.Error和RuntimeException是非检查型异常,其他的都是检查型异常; 2.所有方法都可以在不声明throws的情况下抛出RuntimeException及 ...
- 给IT新男的15点建议:苦逼程序员的辛酸反省与总结
很多人表面上看着老实巴交的,实际上内心比谁都好强.自负.虚荣.甚至阴险.工作中见的多了,也就习惯了. 有一些人,什么事都写在脸上,表面上经常得罪人,甚至让人讨厌.但是他们所表现的又未必不是真性情. 我 ...
- java jvm学习笔记十二(访问控制器的栈校验机制)
欢迎装载请说明出处:http://blog.csdn.net/yfqnihao 本节源码:http://download.csdn.net/detail/yfqnihao/4863854 这一节,我们 ...
- How to easily create popup menu for DevExpress treelist z
http://www.itjungles.com/how-to-easily-create-popup-menu-for-devexpress-treelist.html Adding popup m ...
- 如何解决Rally模板提示angular js加载错误
[前言] Rally是一个开源测试工具,用于测试openstack各个组件的性能 在使用Rally测试完毕后,一般会生成测试报告,这点很重要.但是原生态的Rally报告模板angular js框架是从 ...
- mysql EF
使用 mysql-installer-community-5.6.26.0.msi visual studio 2013 update 4版 Install-Package EntityFramewo ...
- [LeetCode] Ugly Number (A New Question Added Today)
Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers ...
- CreateThread函数&&CString::GetBuffer函数
对这个两个常见的windows下的函数学习了一下: //最简单的创建多线程实例 #include <stdio.h> #include <windows.h> //子线程函数 ...
- RabbitMQ (三) 发布/订阅 -摘自网络
这篇博客中,我们会做一些改变,就是把一个消息发给多个消费者,这种模式称之为发布/订阅(类似观察者模式). 为了验证这种模式,我们准备构建一个简单的日志系统.这个系统包含两类程序,一类程序发动日志,另一 ...
- nginx 502 错误
今天帮朋友处理一个程序报错,重启nginx服务之后,发现首页打不开了,但是静态文件可以打开 经检查nginx 服务器正常运行,重启无数次仍然502错误,考虑到静态文件可以打开,怀疑可能是php 脚本程 ...