linux多线程互斥-售票

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>

int ticket_cnt = 20;     /* 共有20张票 */
typedef struct tag
{
    int s_id;
    pthread_mutex_t *s_p;
}DATA,*pDATA;

void* handler(void *arg )
{
    int id = ((pDATA)arg)->s_id;
    pthread_mutex_t *p_mutex = ((pDATA)arg)-> s_p;
    printf("a window on !: %d \n", id);
    while(1)
    {
        pthread_mutex_lock(p_mutex);
        if(ticket_cnt == 0)
        {
            printf("ticket out! \n");
            pthread_mutex_unlock(p_mutex);
            free((pDATA)arg);
            return (void*)0;
        }
        --ticket_cnt;
        sleep(rand()%3 + 1);
        printf("window: %d : a ticket sold. left : %d \n", id,ticket_cnt );
        pthread_mutex_unlock(p_mutex);
        sleep(rand() % 3 + 1); /* 如果不sleep,锁会一直被这个执行完的线程所占据 */

    }
}

int main(int argc, char *argv[])
{
    srand(getpid());
    pthread_mutex_t mutex;
    pthread_mutex_init(&mutex, NULL);
    int thd_cnt = atoi(argv[1]); /* 从命令行输入卖票窗口数 */
    pthread_t *tds = (pthread_t*)calloc(thd_cnt,sizeof(pthread_t));
    int index;
    for(index = 0; index < thd_cnt; index++ )
    {
        pDATA p = (pDATA)calloc(1,sizeof(DATA));
        p->s_id = index;
        p->s_p = &mutex;
        pthread_create(tds + index , NULL,handler,(void*)p);
    }
    printf("joining...\n");
    for(index = 0; index < thd_cnt; index++)
    {
        pthread_join(tds[index],NULL);
    }
    pthread_mutex_destroy(&mutex);
    return 0;
}

转载于:https://www.cnblogs.com/hxjbc/p/3962098.html

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值