C语言的高级主题涵盖了多线程、网络编程、系统编程等复杂概念。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
// 线程数据结构
typedef struct {
int id;
char* message;
} ThreadData;
// 全局互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 线程函数
void* thread_function(void* arg) {
ThreadData* data = (ThreadData*)arg;
// 使用互斥锁保护共享资源
pthread_mutex_lock(&mutex);
printf("线程 %d 开始执行\n", data->id);
pthread_mutex_unlock(&mutex);
// 模拟工作
sleep(1);
pthread_mutex_lock(&mutex);
printf("线程 %d 完成工作: %s\n", data->id, data->message);
pthread_mutex_unlock(&mutex);
return NULL;
}
// 信号处理函数
void signal_handler(int signum) {
printf("收到信号: %d\n", signum);
if (signum == SIGINT) {
printf("程序被用户中断\n");
exit(0);
}
}
// 简单的TCP服务器
void start_tcp_server(int port) {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
perror("socket创建失败");
return;
}
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(port);
if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
perror("bind失败");
return;
}
if (listen(server_fd, 3) < 0) {
perror("listen失败");
return;
}
printf("服务器监听端口 %d\n", port);
int client_socket = accept(server_fd, NULL, NULL);
if (client_socket < 0) {
perror("accept失败");
return;
}
char buffer[1024] = {0};
read(client_socket, buffer, 1024);
printf("收到消息: %s\n", buffer);
const char* response = "服务器已收到消息";
send(client_socket, response, strlen(response), 0);
close(client_socket);
close(server_fd);
}
// 性能优化示例
void performance_optimization() {
// 使用寄存器变量
register int i;
// 使用内联函数
inline int square(int x) {
return x * x;
}
// 使用位运算优化
int x = 16;
int y = x << 2; // 乘以4
int z = x >> 1; // 除以2
printf("位运算优化: %d * 4 = %d, %d / 2 = %d\n", x, y, x, z);
}
int main() {
// 设置信号处理
signal(SIGINT, signal_handler);
// 创建多个线程
pthread_t threads[3];
ThreadData thread_data[3];
for (int i = 0; i < 3; i++) {
thread_data[i].id = i;
thread_data[i].message = "Hello from thread";
pthread_create(&threads[i], NULL, thread_function, &thread_data[i]);
}
// 等待所有线程完成
for (int i = 0; i < 3; i++) {
pthread_join(threads[i], NULL);
}
// 清理互斥锁
pthread_mutex_destroy(&mutex);
// 启动TCP服务器
printf("\n启动TCP服务器...\n");
start_tcp_server(8080);
// 性能优化示例
printf("\n性能优化示例:\n");
performance_optimization();
return 0;
}