
正文
linux 信号量
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
https://www.jianshu.com/p/6e72ff770244
无名信号量
只适合用于一个进程的不同线程
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <semaphore.h> sem_t sem; void *func1(void *arg)
{
sem_wait(&sem); //一直等待,直到有地方增加信号量,执行之后信号量减一
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(&sem);//增加信号量,加一 pthread_exit(NULL);
} int main(void)
{
int a = ;
sem_init(&sem, , );//初始化信号量
pthread_t thread_id[]; pthread_create(&thread_id[], NULL, func1, (void *)&a);
printf("main thread running.\n");
sleep(5);
pthread_create(&thread_id[], NULL, func2, (void *)&a);
printf("main thread still running.\n");
pthread_join(thread_id[], NULL);
pthread_join(thread_id[], NULL);
sem_destroy(&sem);//销毁信号量 return ;
}
运行结果如下:
线程1虽然先创建,但是要一直等待,直到线程2增加信号量,线程1才能继续执行
命名信号量,可以用于不同进程
#include <time.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <semaphore.h> #define SEM_NAME "/sem_name" //信号量的路径 sem_t *p_sem; void *testThread(void *ptr)
{
sem_wait(p_sem);//信号量减一,信号量为0时阻塞
pthread_exit(NULL);
} int main(void)
{
int i = ;
pthread_t pid;
int sem_val = ;
p_sem = sem_open(SEM_NAME, O_CREAT, , );//初始化信号量为5 if(p_sem == NULL)
{
printf("sem_open %s failed!\n", SEM_NAME);
sem_unlink(SEM_NAME);//解除关联
return -;
} for(i = ; i < ; i++)
{
pthread_create(&pid, NULL, testThread, NULL);
sleep();//等待子线程执行完毕
pthread_join(pid, NULL); //信号量为0之后,子线程将会阻塞,这里也阻塞
sem_getvalue(p_sem, &sem_val);
printf("semaphore value : %d\n", sem_val);
} sem_close(p_sem);//关闭
sem_unlink(SEM_NAME);//解除关联
return ;
}
运行结果:






