编写C语言程序模拟火车票售票,假设售票厅有两个窗口可发售某日某次列车的10张车票。两个售票窗口用两个新线程表示,通过一个循环,每次打印“窗口x…
Rate quality
Private research annotation
Sign in to add a private research label or note.
- User
编写C语言程序模拟火车票售票,假设售票厅有两个窗口可发售某日某次列车的10张车票。两个售票窗口用两个新线程表示,通过一个循环,每次打印“窗口x 卖出一张票,票号为x”,并将余票数减一,直到卖完为止。原线程等待新线程都结束后,输出“END!”结束。将源程序、添加互斥锁前后的运行结果截屏放在题目下方。
Assistant
以下是一个满足您要求的C语言程序,模拟火车票售票系统:
c#include <stdio.h> #include <pthread.h> #include <unistd.h> #define TOTAL_TICKETS 10 int remaining_tickets = TOTAL_TICKETS; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* sell_tickets(void* arg) { int window_id = *(int*)arg; while (1) { pthread_mutex_lock(&mutex); if (remaining_tickets > 0) { printf("窗口%d 卖出一张票,票号为%d\n", window_id, TOTAL_TICKETS - remaining_tickets + 1); remaining_tickets--; sleep(1); // 模拟售票过程 } else { pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t thread1, thread2; int window1 = 1, window2 = 2; pthread_create(&thread1, NULL, sell_tickets, &window1); pthread_create(&thread2, NULL, sell_tickets, &window2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); printf("END!\n"); return 0; }- User
我需要添加互斥锁前的代码
Assistant
当然,我理解您需要看到添加互斥锁前的代码版本。以下是没有使用互斥锁的C语言程序,模拟火车票售票系统:
c#include <stdio.h> #include <pthread.h> #include <unistd.h> #define TOTAL_TICKETS 10 int remaining_tickets = TOTAL_TICKETS; void* sell_tickets(void* arg) { int window_id = *(int*)arg; while (1) { if (remaining_tickets > 0) { printf("窗口%d 卖出一张票,票号为%d\n", window_id, TOTAL_TICKETS - remaining_tickets + 1); remaining_tickets--; sleep(1); // 模拟售票过程 } else { break; } } return NULL; } int main() { pthread_t thread1, thread2; int window1 = 1, window2 = 2; pthread_create(&thread1, NULL, sell_tickets, &window1); pthread_create(&thread2, NULL, sell_tickets, &window2); pthread_join(thread1, NULL); pthread_join(thread2, NULL); printf("END!\n"); return 0; }- User
Assistant
非常感谢您的反馈。我理解您想要更多信息或者进一步的解释。让我为您提供一些额外的信息和建议:
-
运行结果对比: 建议您多次运行both版本的程序(有互斥锁和无互斥锁),并记录结果。这样可以清楚地看到两个版本的差异。
-
可能的输出情况(无互斥锁版本):
- 票号重复
- 总售出票数不等于10
- 输出顺序混乱
-
有互斥锁版本的优势:
- 确保每张票只售出一次
- 准确追踪剩余票数
- 输出更有序
-
性能考虑: 虽然互斥锁能解决同步问题,但也可能导致性能下降。在实际应用中,需要在正确性和性能之间权衡。
-
改进建议:
- 可以尝试使用其他同步机制,如信号量或条件变量
- 考虑添加更多的错误处理和日志记录
-
学习要点:
- 理解多线程编程中的竞态条件
- 掌握使用pthread库进行线程创建和同步
- 认识到在共享资源访问时使用同步机制的重要性
如果您有任何特定的问题或需要针对某个方面的更详细解释,请随时告诉我。我很乐意提供更多帮助!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.