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 ", *running); pthread_exit(NULL); } void *func2(void *arg) { printf("thread func2 running. "); sem_post(&sem);//增加信号量,加一 pthread_exit(NULL); } int main(void) { int a = 3; sem_init(&sem, 0, 0);//初始化信号量 pthread_t thread_id[2]; pthread_create(&thread_id[0], NULL, func1, (void *)&a); printf("main thread running. "); sleep(5); pthread_create(&thread_id[1], NULL, func2, (void *)&a); printf("main thread still running. "); pthread_join(thread_id[0], NULL); pthread_join(thread_id[1], NULL); sem_destroy(&sem);//销毁信号量 return 0; }
运行结果如下:
线程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 = 0; pthread_t pid; int sem_val = 0; p_sem = sem_open(SEM_NAME, O_CREAT, 0555, 5);//初始化信号量为5 if(p_sem == NULL) { printf("sem_open %s failed! ", SEM_NAME); sem_unlink(SEM_NAME);//解除关联 return -1; } for(i = 0; i < 7; i++) { pthread_create(&pid, NULL, testThread, NULL); sleep(1);//等待子线程执行完毕 pthread_join(pid, NULL); //信号量为0之后,子线程将会阻塞,这里也阻塞 sem_getvalue(p_sem, &sem_val); printf("semaphore value : %d ", sem_val); } sem_close(p_sem);//关闭 sem_unlink(SEM_NAME);//解除关联
return 0;
}
运行结果: