面试题答案
一键面试1. 设计数据结构
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
// 定义客户端信息结构体
typedef struct {
int sockfd;
char ip[16];
int port;
} ClientInfo;
// 定义指针数组管理客户端连接
#define MAX_CLIENTS 100
ClientInfo* clientArray[MAX_CLIENTS];
int clientCount = 0;
// 互斥锁
pthread_mutex_t mutex;
2. 添加新客户端连接
void addClient(int sockfd, const char* ip, int port) {
if (clientCount >= MAX_CLIENTS) {
printf("客户端已满,无法添加新客户端\n");
return;
}
pthread_mutex_lock(&mutex);
ClientInfo* newClient = (ClientInfo*)malloc(sizeof(ClientInfo));
newClient->sockfd = sockfd;
strcpy(newClient->ip, ip);
newClient->port = port;
clientArray[clientCount++] = newClient;
pthread_mutex_unlock(&mutex);
}
3. 删除指定客户端连接
void removeClient(int sockfd) {
pthread_mutex_lock(&mutex);
for (int i = 0; i < clientCount; i++) {
if (clientArray[i]->sockfd == sockfd) {
free(clientArray[i]);
for (int j = i; j < clientCount - 1; j++) {
clientArray[j] = clientArray[j + 1];
}
clientCount--;
break;
}
}
pthread_mutex_unlock(&mutex);
}
4. 遍历所有客户端信息
void traverseClients() {
pthread_mutex_lock(&mutex);
for (int i = 0; i < clientCount; i++) {
printf("客户端 %d: sockfd = %d, IP = %s, 端口 = %d\n",
i + 1, clientArray[i]->sockfd, clientArray[i]->ip, clientArray[i]->port);
}
pthread_mutex_unlock(&mutex);
}
5. 多线程环境下保证线程安全性
在多线程环境下,通过使用互斥锁(pthread_mutex_t
)来保证对指针数组操作的线程安全性。在对clientArray
进行添加(addClient
)、删除(removeClient
)和遍历(traverseClients
)操作前,先加锁(pthread_mutex_lock
),操作完成后解锁(pthread_mutex_unlock
)。这样可以防止多个线程同时对指针数组进行操作,避免数据竞争和不一致问题。
在实际应用中,还可以考虑使用读写锁(pthread_rwlock_t
),如果遍历操作频繁而添加和删除操作较少,可以在读操作时使用读锁(允许多个线程同时读),在写操作(添加和删除)时使用写锁(只允许一个线程写),以提高并发性能。