用线程做一个火车票购票系统(可以根据需要选择线程个数)

线程的概述

进程:是系统中程序运行和资源分配的最基本单元,每个进程都有自己独立的存储空间(代码区,数据区,堆栈区)

线程:通常叫做轻量级的进程,拥有自己的执行序列,是进程基本单元,每个进程都至少拥有一个线程也就是main线程;

线程:共享的是进程的存储空间(代码区,数据区),除栈区数据以外,用的都是进程的空间;

线程与进程的区别:

线程:执行开销小,占用CPU的资源少,线程之间切换快,但是不利于资源管理;

进程:恰好相反,可移植性强;

注意:如果是线程相关函数的代码进行编译的时候,后面要加选项:-lpthread

进程与线程之间对比:

创建                退出               等待退出

进程:     fork()                exit()              wait()或waitpid()

线程:   pthread_creat         pthread_exit             pthread_join 

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
int all=50;
int k=1;
pthread_mutex_t lock;
pthread_cond_t cond;
void rountine_func(void*arg)
{
printf("clean up!\n");
}
void *pth_fun1()
{
int a=0;
pthread_cleanup_push(rountine_func,NULL);
while(1)
{
sleep(1);
pthread_mutex_lock(&lock);
if(all<=0)
{
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
if(k<1)
{
pthread_exit(0);
}
k--;
}
all--;
a++;
printf("线程1已购票%d\n",a);
pthread_mutex_unlock(&lock);
}
pthread_cleanup_pop(1);
}
void *pth_fun2()
{
int a=0;
pthread_cleanup_push(rountine_func,NULL);
while(1)
{
sleep(1);
pthread_mutex_lock(&lock);
if(all<=0)
{
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
if(k<=0)
{
pthread_exit(0);
}
k--;
}
all--;
a++;
printf("线程2已购票:%d\n",a);
pthread_mutex_unlock(&lock);
}
pthread_cleanup_pop(1);
}
void *pth_fun3()
{
pthread_cleanup_push(rountine_func,NULL);
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond,&lock);
all+=50;
printf("站票开始出售:票数为%d\n\n",all);
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
pthread_cleanup_pop(1);
}
void *pth_fun4()
{
int a=0;
pthread_cleanup_push(rountine_func,NULL);
while(1)
{
sleep(1);
if(all!=50)
{
pthread_mutex_lock(&lock);
if(a==20)
{
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
all++;
a++;
printf("线程4已退票:%d\n",a);
pthread_mutex_unlock(&lock);
}
else
printf("\n");
}
pthread_cleanup_pop(1);
}
int main()
{
pthread_mutex_init(&lock,NULL);
pthread_t thread1;
if(pthread_create(&thread1,NULL,pth_fun1,NULL)==-1)
{
printf("create error!\n");
exit(1);
}
pthread_t thread2;
if(pthread_create(&thread2,NULL,pth_fun2,NULL)==-1)
{
printf("create error!\n");
exit(1);
}
pthread_t thread3;
if(pthread_create(&thread3,NULL,pth_fun3,NULL)==-1)
{
printf("create error!\n");
exit(1);
}
pthread_t thread4;
if(pthread_create(&thread4,NULL,pth_fun4,NULL)==-1)
{
printf("create error!\n");
exit(1);
}
pthread_cleanup_push(rountine_func,NULL);
pthread_cond_init(&cond,NULL);
pthread_mutex_init(&lock,NULL);
while(1)
{
if(all<=0)
{
pthread_exit(0);
}
printf("剩余票数:%d\n",all);
sleep(1);
}
pthread_mutex_destory(&lock);
pthread_cond_destroy(&cond);
pthread_cleanup_pop(1);
return 0;
}



posted @ 2017-08-16 20:58  我大概是只废喵  阅读(637)  评论(0编辑  收藏  举报