linux 线程编程:信号量
来源:互联网 发布:php许愿墙源码 编辑:程序博客网 时间:2024/05/17 08:03
今天写一下用于线程间同步的信号量,使用信号量可以实现任务的同步工作以及资源的同步访问等,信号量的使用与互斥锁很像:初始化,操作,销毁。
相关函数
#include <semaphore.h>
int sem_init (sem_t* sem, int pshared, unsigned int value);
int sem_wait(sem_t *sem);
int sem_trywait (sem_t* sem);
int sem_post(sem_t *sem);
int sem_getvalue (sem_t* sem);
int sem_destroy (sem_t* sem);
测试代码
#include <stdio.h>#include <string.h>#include <pthread.h>#include <semaphore.h>void *tfunc_put(void *arg);void *tfunc_get(void *arg);typedef struct test_sem{unsigned char value;sem_t sem_put;sem_t sem_get;}test_sem_t;test_sem_t test;int main(int argc, char **argv){int ret = -1;pthread_t tid_1;pthread_t tid_2;sem_t sem;memset(&test, 0, sizeof(test));sem_init(&test.sem_put, 0, 0); //初始化信号量.sem_init(&test.sem_get, 0, 0);ret = pthread_create(&tid_1, NULL, tfunc_put, NULL);if(0 != ret){printf("[%s:%d] create thread fail\n", __func__, __LINE__);}ret = pthread_create(&tid_2, NULL, tfunc_get, NULL);if(0 != ret){printf("[%s:%d] create thread fail\n", __func__, __LINE__);}ret = pthread_join(tid_1, NULL);if(0 != ret){printf("[%s:%d] join thread fail\n", __func__, __LINE__);}ret = pthread_join(tid_2, NULL);if(0 != ret){printf("[%s:%d] join thread fail\n", __func__, __LINE__);}sem_destroy(&test.sem_put); //销毁信号量.sem_destroy(&test.sem_get);return 0;}void *tfunc_put(void *arg){int i = 0;for(i=0; i<4; i++){test.value = i;sem_post(&test.sem_put);sem_wait(&test.sem_get);}pthread_exit(NULL);}void *tfunc_get(void *arg){int i = 0;for(i=0; i<4; i++){sem_wait(&test.sem_put);printf("[%s:%d]test.value:%d\n", __func__, __LINE__, test.value);sem_post(&test.sem_get);}pthread_exit(NULL);}
运行结果
使用信号量
[tfunc_get:80]test.value:0
[tfunc_get:80]test.value:1
[tfunc_get:80]test.value:2
[tfunc_get:80]test.value:3
不使用信号量
[tfunc_get:80]test.value:0
[tfunc_get:80]test.value:3
[tfunc_get:80]test.value:3
[tfunc_get:80]test.value:3
0 0
- linux 线程编程:信号量
- Linux 信号量 与 线程编程
- linux程序设计 线程 多线程编程 信号量
- linux系统编程:线程同步-信号量(semaphore)
- Linux线程编程 - 线程同步机制之信号量
- Linux多线程编程之同步对象编程:线程信号量
- 线程编程之信号量
- linux下编程学习----- 线程同步之无名信号量
- linux下编程学习----- 线程同步之无名信号量
- linux下编程学习----- 线程同步之无名信号量
- linux多线程编程(C):信号量实现的线程安全队列
- 【Linux】生产者消费者编程实现-线程池+信号量
- 【Linux】生产者消费者编程实现-线程池+信号量
- Linux多线程编程(四)线程同步之信号量
- Linux信号量线程控制
- linux 线程 信号量
- Linux信号量线程控制
- linux线程学习-信号量
- Memcached笔记——(三)Memcached使用总结
- Memcached笔记——(四)应对高并发攻击
- SQl server error:40 错误2
- 2D绘图
- C++ this指针(2) - this指针的类型
- linux 线程编程:信号量
- xmemcached使用的几点优化建议
- 黑马程序员-----高新技术-----Java内省机制细讲
- 机器学习总结(1)
- 硬编码学习(四)
- 判断当前登录的终端是PC端还是移动端
- 图像处理编程实现中需要注意的数据类型问题
- PHP输入流php://input介绍
- web开发笔记(7):jQuery自带的前台日历插件WdatePicker