
C 语言多线程编程:解决问题的艺术与实践
引言
多线程编程是一种并行编程技术,它允许应用程序同时执行多个任务。在 C 语言中,多线程使用以下函数实现:
pthread_create() - 创建新线程pthread_join() - 等待线程完成pthread_mutex_lock() - 获取互斥锁pthread_mutex_unlock() - 释放互斥锁实战案例:文件复制
立即学习“C语言免费学习笔记(深入)”;
考虑一个 C 语言应用程序,它需要复制大量文件从一个目录到另一个目录。使用多线程,我们可以加快此过程,同时执行以下步骤:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 线程函数
void *thread_copy_file(void *arg) {
// 获取文件路径
char *filepath = (char *)arg;
// 打开文件
FILE *src_file = fopen(filepath, "r");
if (src_file == NULL) {
perror("无法打开源文件");
pthread_exit(NULL);
}
// 创建目标文件
char *dest_file = malloc(strlen(filepath) + 1);
strcpy(dest_file, filepath);
strcat(dest_file, ".copy");
// 复制文件
FILE *dest = fopen(dest_file, "w");
if (dest == NULL) {
perror("无法打开目的文件");
pthread_exit(NULL);
}
int c;
while ((c = getc(src_file)) != EOF) {
putc(c, dest);
}
// 关闭文件
fclose(src_file);
fclose(dest);
// 线程退出
pthread_exit(NULL);
}
int main() {
int num_threads;
// 获取要复制的文件列表
printf("输入要复制的文件数量:");
scanf("%d", &num_threads);
// 创建线程数组
pthread_t threads[num_threads];
// 创建并启动线程
for (int i = 0; i < num_threads; i++) {
char *filepath = malloc(100);
printf("输入第 %d 个文件的路径:", i + 1);
scanf("%s", filepath);
pthread_create(&threads[i], NULL, thread_copy_file, filepath);
}
// 等待线程完成
for (int i = 0; i < num_threads; i++) {
pthread_join(threads[i], NULL);
}
printf("所有文件已复制成功!\n");
return 0;
}结论
多线程编程是一种强大的用于提高应用程序性能的技术。通过遵循本文中概述的步骤,你可以有效地使用 C 语言的线程功能,以解决复杂的问题并优化你的应用程序的并行性。
以上就是C语言多线程编程:问题解决的艺术与实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号