码迷,mamicode.com
首页 > 编程语言 > 详细

linux多线程互斥-售票

时间:2014-09-09 12:13:48      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:des   io   ar   for   on   c   amp   linux   ad   

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

linux多线程互斥-售票

标签:des   io   ar   for   on   c   amp   linux   ad   

原文地址:http://www.cnblogs.com/hxjbc/p/3962098.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!