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 
", id);
    while(1)
    {
        pthread_mutex_lock(p_mutex);
        if(ticket_cnt == 0)
        {
            printf("ticket out! 
");
            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 
", 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...
");
    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