结构体定义如下:
struct timespec {time_t tv_sec;/* Seconds */longtv_nsec;/* Nanoseconds [0 .. 999999999] */}; 如果指定的阻塞时间到了 , 但是 sem 仍然小于 0, 则会返回一个错误 (错误设置为 ETIMEDOUT ) 。
post(V)post 为信号量值加一操作 , 函数原型如下:
#include int sem_post(sem_t *sem);Link with -pthread.返回值:若成功 , 返回 0 ;若出错 , 返回-1无名信号量接口函数信号量的函数都以sem_开头 , 线程中使用的基本信号函数有4个 , 他们都声明在头文件semaphore.h中 , 该头文件定义了用于信号量操作的sem_t类型:
sem_init
该函数用于创建信号量 , 原型如下:
int sem_init(sem_t *sem, int pshared, unsigned int value);功能:该函数初始化由sem指向的信号对象 , 设置它的共享选项 , 并给它一个初始的整数值 。 pshared控制信号量的类型 , 如果其值为0 , 就表示信号量是当前进程的局部信号量 , 否则信号量就可以在多个进程间共享 , value为sem的初始值 。 返回值:该函数调用成功返回0 , 失败返回-1 。
sem_destroy
该函数用于对用完的信号量进行清理 , 其原型如下:
int sem_destroy(sem_t *sem);返回值:
成功返回0 , 失败返回-1 。
sem_getvalue函数
该函数返回当前信号量的值 , 通过restrict输出参数返回 。 如果当前信号量已经上锁(即同步对象不可用) , 那么返回值为0 , 或为负数 , 其绝对值就是等待该信号量解锁的线程数 。
int sem_getvalue(sem_t *restrict, int *restrict);使用实例
【实例1】:
#include #include #include #include #include #include #include #include sem_t sem;#define handle_error(msg)do { \perror(msg); \exit(EXIT_FAILURE); \}while (0)static void handler(int sig){write(STDOUT_FILENO, "sem_post() from handler\n", 24);if(sem_post(_exit(EXIT_FAILURE);}}int main(int argc, char *argv[]){int s;struct timespec ts;struct sigaction sa;if (argc != 3){fprintf(stderr, "Usage: %s\n", argv[0]);exit(EXIT_FAILURE);}if (sem_init(/* Establish SIGALRM handler; set alarm timer using argv[1] */sa.sa_handler = handler;sigemptyset(sa.sa_flags = 0;if (sigaction(SIGALRM,alarm(atoi(argv[1]));/* Calculate relative interval as current time plusnumber of seconds given argv[2] */if (clock_gettime(CLOCK_REALTIME,ts.tv_sec += atoi(argv[2]);printf("main() about to call sem_timedwait()\n");while ((s = sem_timedwait(/* Restart if interrupted by handler *//* Check what happened */if (s == -1){if (errno == ETIMEDOUT)printf("sem_timedwait() timed out\n");elseperror("sem_timedwait");}else{printf("sem_timedwait() succeeded\n");}exit((s == 0) ? EXIT_SUCCESS : EXIT_FAILURE);}【实例2】:
#include #include #include #include #include #include #include #include sem_t sem;void *func1(void *arg){sem_wait(int *running = (int *)arg;printf("thread func1 running : %d\n", *running);pthread_exit(NULL);}void *func2(void *arg){printf("thread func2 running.\n");sem_post(pthread_exit(NULL);}int main(void){int a = 3;sem_init(pthread_t thread_id[2];pthread_create(printf("main thread running.\n");sleep(10);pthread_create(printf("main thread still running.\n");pthread_join(thread_id[0], NULL);pthread_join(thread_id[1], NULL);sem_destroy(return 0;}
推荐阅读
-
家里客厅摆什么植物比较好 家里客厅摆什么植物比较好看
-
服饰搭配|阔腿裤过时了?今夏最显瘦时髦的3条裤子长这样!
-
-
-
爱因斯坦:宇宙膨胀速度已超光速,爱因斯坦早已预言:人类终将见到高维生物
-
-
建议|【卫健要闻】世卫组织:预计疫情持续时间较长,需有长期应对措施
-
同比增长|渤海银行上半年净利50亿增2.5%,不良贷款率1.78%
-
-
-
「南宁」“人民出行”在广西南宁打造全国首个5G慢行交通试点 正式登记上牌
-
中年|海南离岛免税经营主体可市场化竞争进入,概念股再掀涨停潮丨牛熊眼
-
「新京报经济新闻」国家发改委:推进互联网+,加强5G、工业互联网建设
-
玉米密植高产示范田最高亩产达1663.25公斤 刷新玉米亩产全国纪录
-
明星穿搭|5位“真的在赶飞机”的明星:王鹤棣飞奔,雷佳音造型“抢眼”!
-
美军:让中国不可能赢?美国计划采取军事行动,向中国发出强烈信号
-
-
-
卡纳瓦罗|耻辱性1-7!两大归化前锋看台上“排排坐”,卡纳瓦罗应怀念两人
-