操作系统原理-课后作业4
第四题
模拟售票:10张票由2个窗口(线程)售出
代码如下:
保存为saleTickets.cpp
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int tickets=10;//定义票数为全局变量,所有线程都可访问
pthread_mutex_t mutex;//定义互斥锁
void delay()//自定义延迟函数,不可使用sleep
{
int x=rand()%30000;
int y;
while(x>0)
{
y=rand()%30000;
while(y>0)
y--;
x--;
}
}
void *saleTick(void *arg)
{
int cur_tickets;//定义当前票数
while(1)
{
pthread_mutex_lock(&mutex);//加锁
cur_tickets=tickets;
if(cur_tickets<=0)
{
pthread_mutex_unlock(&mutex);
break;
}
printf("当前票数为:%d\n",cur_tickets);
delay();//随机延迟
cur_tickets--;
tickets=cur_tickets;//把当前票数返回给全局变量,让所有线程都知道
pthread_mutex_unlock(&mutex);//解锁
}
}
int main()
{
pthread_t tid[2]={0};//定义2个线程ID
int ret,i;
srand(time(NULL));//初始化随机函数
ret=pthread_mutex_init(&mutex,NULL);//初始化互斥锁
if(0!=ret)//初始化失败返回0
{
perror("pthread_nutex_init");
exit(1);
}
for(i=0;i<2;i++)//模拟2个线程同时运行
{
ret=pthread_create(&tid[i],NULL,saleTick,NULL);//创建线程
if(0!=ret)//创建失败
{
perror("pthread_creat");
exit(1);
}
}
for(i=0;i<2;i++)
{
pthread_join(tid[i],NULL);//线程等待
}
pthread_mutex_destroy(&mutex);//最后销毁互斥锁
return 0;
}
运行后报错:
/tmp/ccqvFrJC.o:
在函数‘main’中:
saleTickets.cpp:(.text+0x17c):对‘pthread_create’未定义的引用
saleTickets.cpp:(.text+0x1c3):对‘pthread_join’未定义的引用
collect2:error: ld returned 1exit status
原因:pthread库不是Linux系统默认的库,
连接时需要使用库libpthread.a.
所以在使用pthread_create创建线程时,
在编译中要加-lpthread参数:
gcccreateThread.c -lpthread -o createThread.
加上这个以后编译成功!
成功!