首页 > 代码库 > 多线程编程:同时使用信号量与互斥锁
多线程编程:同时使用信号量与互斥锁
#include <pthread.h> #include <semaphore.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <cerrno> #define CUSTOMER_NUM 10 pthread_mutex_t mutex_x= PTHREAD_MUTEX_INITIALIZER; sem_t sem; int sem_val = 0; int iRet; void * get_service(void *thread_id){ int customer_id = *((int *)thread_id); if(sem_wait(&sem) == 0) { sem_getvalue(&sem, &sem_val); //printf("\n"); printf(".......可用窗口 --%d ...\n", sem_val+1); iRet=pthread_mutex_trylock(&mutex_x); if(iRet==EBUSY){ printf ("窗口被占用 请更换服务窗口.\n"); }else if(iRet==0) { printf("customer %d receive service ...\n", customer_id); usleep(1000); /* service time: 100ms */ printf("customer %d receive service over\n", customer_id); pthread_mutex_unlock(&mutex_x); } sem_post(&sem); } } int main(int argc, char *argv[]){ sem_init(&sem,0,2); pthread_t customers[CUSTOMER_NUM]; int i, iRet; for(i = 0; i < CUSTOMER_NUM; i++){ int customer_id = i; iRet = pthread_create(&customers[i], NULL, get_service, &customer_id); if(iRet){ perror("pthread_create"); return iRet; } else{ printf("Customer %d arrived.\n", i); } usleep(200); } int j; for(j = 0; j < CUSTOMER_NUM; j++) { pthread_join(customers[j], NULL); } sem_destroy(&sem); return 0; }
多线程编程:同时使用信号量与互斥锁
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。