结构体定义如下:
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;}
推荐阅读
-
-
『求职』我国最受欢迎的三所师范大学,实力强,含金量高,找工作比较容易
-
-
浙江省|与前夫结婚前,杭州失踪女子和许国利是男女朋友
-
紧急|2009年,“沙师弟”拍完《西游记》紧急住院,成马德华一生的痛
-
-
【中新经纬】年薪百万的职位“光环”不再?他们大批面临困境
-
怎样维权带我飞旅行app虚假机票诈骗消费者不退款(曝光诈骗公司“带我飞”)
-
sally200403|我太难了!苏亚雷斯为去尤文参加意大利语考试,考试通过才能拿护照
-
迷途的羔羊|适合秋冬季节,让你一秒切换时髦范的穿搭范本!强盛气场晋升气质
-
-
-
|足坛偏见:幸存者偏差!为什么巴西球员职业生涯都不长?
-
-
-
-
奇威娱乐:男神女神都老了,87版《红楼梦》“贾宝玉、王熙凤”和赵忠祥同框
-
明星整容|她曾是快女的冠军,整容失败后成“怪物”,只剩下眼珠是原装!
-
-
清华金融评论:| 国际,王有鑫:从四大就业指标看美国经济衰退风险