Linux下多线程的实现与控制1.在main线程中创建两个新的线程,其中一个线程用于卖票,一个线程用于补票,假设原始票数5张,只有当票都买完,才补票。编写代码
时间: 2024-10-22 18:08:38 浏览: 19
在Linux环境下,可以使用POSIX线程库(pthreads)或C++11标准中的`std::thread`来实现多线程。这里是一个简单的示例,使用`pthread_create`函数创建两个线程,模拟卖票和补票操作:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define TOTAL_TICKETS 5
void* sell_tickets(void* arg) {
int tickets = TOTAL_TICKETS;
while (tickets > 0) {
printf("Ticket sold: %d\n", tickets);
tickets--;
// 模拟售票操作,实际应用中可能会有更复杂的逻辑
pthread_mutex_lock(&ticket_mutex); // 锁定票务资源
if (tickets == 0) {
printf("All tickets sold, starting to replenish.\n");
pthread_cond_signal(&replenish_condition); // 发送信号通知补票线程
}
pthread_mutex_unlock(&ticket_mutex); // 解锁
}
return NULL;
}
void* replenish_tickets(void* arg) {
pthread_mutex_lock(&ticket_mutex); // 等待卖票线程结束并释放锁
printf("Replenishing tickets...\n");
while (TRUE) {
pthread_cond_wait(&replenish_condition, &ticket_mutex); // 等待信号
if (TOTAL_TICKETS < tickets + 1) { // 当所有票售完后,开始补票
break;
}
// 补充票务,实际应用中可能需要持久化处理
TOTAL_TICKETS++;
printf("Tickets replenished to: %d\n", TOTAL_TICKETS);
}
pthread_mutex_unlock(&ticket_mutex);
return NULL;
}
int main() {
pthread_t sell_thread, replenish_thread;
pthread_mutex_t ticket_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t replenish_condition = PTHREAD_COND_INITIALIZER;
if (pthread_create(&sell_thread, NULL, sell_tickets, NULL)) {
perror("Error creating sell thread");
exit(1);
}
if (pthread_create(&replenish_thread, NULL, replenish_tickets, NULL)) {
perror("Error creating replenish thread");
exit(1);
}
pthread_join(sell_thread, NULL);
pthread_join(replenish_thread, NULL);
printf("Threads finished, exiting.\n");
return 0;
}
阅读全文