#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <errno.h>
#include <getopt.h>
#include <sched.h>
#include <basetypes.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/signal.h>
#include <pthread.h>
#include <semaphore.h>
extern int init_sem();
extern int deinit_sem();
extern int signal_sem();
static sem_t g_sem;
static pthread_t pl_thread;
int init_sem()
{
int res = 0;
if(0 != sem_init(&g_sem,0,0)) //pshared不为0时此信号量在进程间共享,否则只能为当前进程的所有线程共享;
{
perror("sem_init"); //value给出了信号量的初始值。
res = -1;
}
return res;
}
int signal_sem()
{
int res = 0;
if(0 != sem_post(&g_sem)) //是给信号量的值加上一个“1”
{
perror("sem_post");
res = -1;
}
return res;
}
int deinit_sem()
{
int res = 0;
if( 0 != sem_destroy(&g_sem))
{
res = -1;
}
return res;
}
int wait_sem(int ms)
{
int res = 0;
if(ms == 0)
{
if(0 != sem_wait(&g_sem)) //它的作用是从信号量的值减去一个“1”,
{
perror("sem_wait");
res = -1;
}
}
else
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME,&ts);
ts.tv_sec += ms/1000;
ts.tv_nsec += (ms%1000)*1000000;
if(0 != sem_timedwait(&g_sem,&ts)) // int sem_timedwait(sem_t*sem,const struct timespec*abs_timeout) //utc 时间
{
perror("sem_timedwait");
res = -1;
}
}
return res;
}
void * pl_loop(void * data)
{
signal_sem();
return NULL;
}
int main(int argc, char **argv)
{
int ret = -1;
init_sem();
if (pthread_create(&pl_thread, NULL, (void *)pl_loop,(void *)NULL) != 0)
{
}
if(0 != wait_sem(0))
{
}
else
{
}
deinit_sem();
printf("deinit sem\n");
while(1)
{
sleep(1);
}
return 0;
}
控制线程运转之信号灯
最新推荐文章于 2024-08-09 05:25:47 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)