多线程编程:同时使用信号量与互斥锁

Posted 栀子花开

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程编程:同时使用信号量与互斥锁相关的知识,希望对你有一定的参考价值。

#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;
}

 

以上是关于多线程编程:同时使用信号量与互斥锁的主要内容,如果未能解决你的问题,请参考以下文章

linux下信号量和互斥锁的区别

多线程之线程同步(互斥锁信号量条件变量和读写锁​)

多线程之线程同步(互斥锁信号量条件变量和读写锁​)

多线程之线程同步(互斥锁信号量条件变量和读写锁​)

12第七周-网络编程 - 线程中的信号量(Semaphore)

详解linux多线程——互斥锁条件变量读写锁自旋锁信号量