Linux信号量sem_t简单实例运用
2017-05-02 20:10
246 查看
sem_t sem;
定义一个信号量变量。使用时需首先使用sem_init()函数初始化。
在多线程编程中,想让某个线程阻塞等待,减少cpu占用,在该需要运行时才运行。使用信号量一个A线程sem_wait(),阻塞等待;一个B线程在需要运行A线程时sem_post(),解除A线程阻塞。
下面是简单demo:
定义一个信号量变量。使用时需首先使用sem_init()函数初始化。
在多线程编程中,想让某个线程阻塞等待,减少cpu占用,在该需要运行时才运行。使用信号量一个A线程sem_wait(),阻塞等待;一个B线程在需要运行A线程时sem_post(),解除A线程阻塞。
下面是简单demo:
#include <stdint.h> #include <semaphore.h> #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> sem_t sem; void *testfunc(void *arg) { while(1) { sem_wait(&sem); //do something.... printf("hello world...\n"); } } int main() { pthread_t ps; sem_init(&sem, 0, 0); pthread_create(&ps,NULL,testfunc,NULL); while(1) { //每隔一秒sem_post 信号量sem加1 子线程sem_wait解除等待 打印hello world sem_post(&sem); sleep(1); } return 0; }
相关文章推荐
- linux的ipc信号量简单实例
- semExample.c(linux下信号量使用实例)
- linux c++多线程互斥锁和信号量简单实例
- linux的进程通信:信号量实例(C语言)
- Linux Socket编程简单实例
- Linux下基于C实现的socket简单文件上传实例
- Linux下基于C实现的socket简单文件下载实例
- [编程实例]linux下的以太网简单网络流量分析
- Linux 网络编程 简单实例
- [Linux网络编程]ARP简单实例
- Linux Socket编程简单实例
- Linux的Makefile简单实例教程
- 一个简单的linux下网络程序实例-网络编程入门
- Linux下JNI调用简单实例操作全过程
- 简单标签的简介和实例运用
- linux下DHCP简单配置实例
- linux 一个简单守护进程实例
- LINUX 简单的串口读写实例
- Linux信号量 sem_t简介
- Linux信号量编程实例