自学内容网 自学内容网

Linux——互斥与同步练习

用多线程程序设计一个火车票售票系统,
要求至少有两个售票窗口,每个售票窗口
不能重复买票,将100张车票均匀的从两个
窗口卖出即可。

./a.out 
窗口1 卖出车票 1
窗口2 卖出车票 2
窗口1 卖出车票 3
窗口2 卖出车票 4
.....


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
int num=100;
int WIN[2]={1,1};
sem_t sem_WIN;
pthread_mutex_t mutex;
pthread_mutex_t mutex_win;
int get_win()
{

    sem_wait(&sem_WIN);
    int i = 0 ;
    for(i = 0 ;i<2;i++)
    {
        pthread_mutex_lock(&mutex_win);
        if(1==WIN[i])
        {
            WIN[i] = 0 ;
            pthread_mutex_unlock(&mutex_win);

            return i;
        }else 
        {
            pthread_mutex_unlock(&mutex_win);
        }
    }

    return -1;

}
void relese_win(int id)
{
    pthread_mutex_lock(&mutex_win);
    WIN[id]=1;
    pthread_mutex_unlock(&mutex_win);
    sem_post(&sem_WIN);
}
void* th(void* arg)
{

    while(1)
    {
        pthread_mutex_lock(&mutex);
        if(num>0)
        {
            int n = num--;
            pthread_mutex_unlock(&mutex);
            int id = get_win();
            printf("win %d, ticket:%d tid:%lu\n",id+1 ,n,pthread_self());
            usleep(1000*100);
            relese_win(id);
        }else
        {
            pthread_mutex_unlock(&mutex);
            break;
        }

    }
    return NULL;

}
int main(int argc, char *argv[])
{
    pthread_t tid1,tid2;
    pthread_mutex_init(&mutex,NULL);
    pthread_mutex_init(&mutex_win,NULL);
    sem_init(&sem_WIN,0,2);
    pthread_create(&tid1,NULL,th,NULL);
    pthread_create(&tid2,NULL,th,NULL);
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    sem_destroy(&sem_WIN);
    pthread_mutex_destroy(&mutex);
    pthread_mutex_destroy(&mutex_win);
    return 0;
}

启动三个线程,th1输出a,th2输出b,th3输出c。输出
abcabcabcabc。 10个abc

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
#include<semaphore.h>
sem_t sem1,sem2,sem3;
void *th1(void*arg)
{
int i=10;
while(i--)
{
sem_wait(&sem1);
printf("a");
fflush(stdout);
sem_post(&sem2);
}
return NULL;

}

void *th2(void *arg)
{
int i=10;
while(i--)
{
sem_wait(&sem2);
printf("b");
sleep(1);
fflush(stdout);
sem_post(&sem3);
}
return NULL;


}
void *th3(void *arg)
{
int i=10;
while(i--)
{
sem_wait(&sem3);


printf("c");
sleep(1);
fflush(stdout);
sem_post(&sem1);
}
return NULL;


}

int main(int argc, const char *argv[])
{
pthread_t tid1,tid2,tid3;
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
    pthread_create(&tid1,NULL,th1,NULL);
    pthread_create(&tid2,NULL,th2,NULL);
    pthread_create(&tid3,NULL,th3,NULL);

pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_join(tid3,NULL);

    sem_destroy(&sem1);
    sem_destroy(&sem2);
    sem_destroy(&sem3);
    return 0;


}


原文地址:https://blog.csdn.net/m0_71703182/article/details/140117971

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!