#include<stdio.h> #include<pthread.h> #include<unistd.h> int tickets = 15; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void * sell_tickets1(void *arg){ while (1) { pthread_mutex_lock(&mutex1); if(tickets > 0) { printf("W1: %d tickets are left\n",tickets--); } else { pthread_mutex_unlock(&mutex1); break; } pthread_mutex_unlock(&mutex1); sleep(1); } printf("W1: 10 tickets were sold from window 1\n"); return NULL; } void * sell_tickets2(void *arg){ while (1) { pthread_mutex_lock(&mutex1); if(tickets > 0) { printf("W2: %d tickets are left\n",tickets--); } else { pthread_mutex_unlock(&mutex1); break; } pthread_mutex_unlock(&mutex1); sleep(2); } printf("W2: 5 tickets were sold from window 2\n"); return NULL; } int main() { pthread_t t1,t2; pthread_create(&t1, NULL, sell_tickets1, NULL); pthread_create(&t2, NULL, sell_tickets2, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); return 0; }
时间: 2024-01-15 16:03:14 浏览: 25
这段代码是一个经典的多线程编程例子,用于模拟两个售票窗口售卖15张票的过程。主要涉及到线程的创建、互斥锁的使用等。
在该程序中,tickets变量表示剩余票数,sell_tickets1和sell_tickets2是两个线程函数,分别表示两个售票窗口的售票过程。互斥锁mutex1用于保证线程间对tickets变量的访问不会出现竞争条件。具体实现中,每个线程在访问tickets变量之前都会先对mutex1进行加锁,然后进行售票操作,最后再释放锁。当剩余票数为0时,线程退出循环,释放锁。
该程序中使用了pthread库中的相关函数,如pthread_mutex_lock、pthread_mutex_unlock、pthread_create、pthread_join等。
需要注意的是,该程序在两个线程中分别使用了不同的睡眠时间,即sell_tickets1中睡眠1秒,sell_tickets2中睡眠2秒。这是为了模拟不同售票窗口的售票速度不同,同时也能更好地展示多线程编程带来的效果。
相关问题
#include <stdio.h> \\DUNWEICHAO
引用: "#include <stdio.h>" 是C语言中的预处理指令,用于包含标准输入输出库(stdio.h)的内容[^1]。引用:同样的,"#include <stdio.h>" 也是C语言中的预处理指令,用于包含标准输入输出库(stdio.h)的内容[^2]。
在C语言中,stdio.h是一个头文件,它包含了一些用于输入和输出的函数、宏和定义。通过包含这个头文件,我们可以使用标准输入输出函数(如printf和scanf)来进行输入和输出操作。stdio.h提供了一些常用的函数,例如文件操作、字符输入输出、格式化输入输出等等。这个头文件是C语言中最常用的头文件之一,几乎所有的C程序都会包含它。
所以,当我们在C语言程序中使用"#include <stdio.h>"时,我们可以使用stdio.h中定义的函数和宏来进行输入和输出操作。
范例:在C语言中使用stdio.h进行输出操作。
```c
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
```
#include<iostream>与#include<stdio.h>的区别
#include<iostream> 和#include<stdio.h>是两个不同的头文件引用语句,它们有以下区别:
1. 功能:#include<iostream> 是C++标准库中的头文件,用于输入输出操作,包含了cin、cout等对象和函数的定义。而#include<stdio.h>是C语言标准库中的头文件,用于输入输出操作,包含了printf、scanf等函数的定义。
2. 命名空间:#include<iostream> 引入的是std命名空间,需要使用std::cout、std::cin等来访问其中的元素。而#include<stdio.h>没有命名空间的概念,函数名直接使用即可。
3. 扩展名:#include<iostream> 的头文件没有扩展名,因为它是C++标准库中的头文件。而#include<stdio.h>的头文件扩展名为.h,因为它是C语言标准库中的头文件。
4. 文件位置:#include<iostream> 是C++标准库中的头文件,通常位于编译器的include路径中。而#include<stdio.h>是C语言标准库中的头文件,也位于编译器的include路径中。
总之,#include<iostream> 用于C++程序中,提供了更方便的输入输出操作;而#include<stdio.h> 用于C程序中,提供了基本的输入输出功能。