模拟售票:10张票由2个窗口(线程)售出

操作系统原理-课后作业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.

加上这个以后编译成功!

成功!

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值