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