我是靠谱客的博主 阳光过客,最近开发中收集的这篇文章主要介绍有名信号量的使用,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

sem.c

//sem.c
/* when compile,should link lib pthread.
like this: $(CC) sem.c -o sem -lpthread
*/
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/semaphore.h>// this is on mac,on ubuntu is #include <semaphore.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/param.h>
#include <signal.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h> // sleep()
#define SECOND_USEC (1000000)
static sem_t * s;
void ossal_usleep(unsigned long usec)
{
struct timeval tv;
tv.tv_sec = (time_t) (usec / SECOND_USEC);
tv.tv_usec = (long) (usec % SECOND_USEC);
select(0, (fd_set *) 0, (fd_set *) 0, (fd_set *) 0, &tv);
}
/**
* 带超时的等待信号量
* @param
b
信号量
* @param
usec 微妙
* @return
成功0,失败-1
*/
int my_sem_take(sem_t*
b, int usec)
{
sem_t *s = (sem_t *) b;
int err;
int time_wait = 1;
/* Retry algorithm with exponential backoff(指数补偿) */
for (;;) {
if (sem_trywait(s) == 0) {
err = 0;
break;
}
if (errno != EAGAIN && errno != EINTR) {
err = errno;
break;
}
if (time_wait > usec) {
time_wait = usec;
}
ossal_usleep(time_wait);
usec -= time_wait;
if (usec == 0) {
err = ETIMEDOUT;
break;
}
if ((time_wait *= 2) > 100000) {
time_wait = 100000;
}
}
return err ? -1 : 0;
}
void * thr_fn(void *arg)
{
printf("thread 1 startn");
while(1)
{
printf("就像你的温柔,无法挽留n");
sleep(2);
sem_post(s);
break;
}
pthread_exit((void*)0);
}
int main (int argc, char *argv[])
{
int ret;
char *sem_name = "sem_file";
pthread_t tid;
s = sem_open(sem_name, O_CREAT, 0644, 0);
if(s == SEM_FAILED)
{
perror("sem_open");
exit(-1);
}
ret = pthread_create(&tid, NULL, thr_fn, NULL);
if (ret != 0)
{
perror("pthread_create");
exit(-1);
}
printf("我像风一样自由....n");
ret = my_sem_take(s, 5*1000*1000);
printf("ret = %dn", ret);
sem_close(s);
//有名信号量需要用sem_unlink来销毁,否则下一次sem_open会残留上一次的值
if(0 != sem_unlink(sem_name))
{
perror("sem_unlink");
}
return EXIT_SUCCESS;
}

Makefile

#Makefile
sem: sem.c
$(RM) sem *.o
gcc $^ -o $@ -lpthread

最后

以上就是阳光过客为你收集整理的有名信号量的使用的全部内容,希望文章能够帮你解决有名信号量的使用所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部