c++ - 使用多线程读取同一个文件失败
问题描述
我创建了 50 个线程来同时读取同一个文件,然后在每个线程中,尝试将其内容写入使用不同名称创建的新文件。该代码应该生成 50 个不同的文件。但我得到了意想不到的结果,它只生成了 3~5 个文件。
当所有人读取同一个文件时,没有竞争条件,每个线程都旨在将其内容写入不同的文件。
有人可以帮助我吗?谢谢!
下面列出了我的代码,它是对参考的修改
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <iostream>
#include <vector>
#include <thread>
void copy(const char *src_path, const char *dst_path);
int main(int argc, char **argv)
{
std::vector<std::thread> vth;
char *tmp = "Copy.deb";
for (int i = 0; i < 50; ++i)
{
char src[40];
memset(src, '\0', sizeof(src));
sprintf(src, "%d", i);
strcat(src, tmp);
vth.emplace_back(std::bind(copy, "Original.deb", strdup(src)));
}
for (int i = 0; i < 50; ++i)
{
vth[i].join();
}
return 0;
}
void copy(const char *src_path, const char *dst_path)
{
FILE *src, *dst;
int buffer_size = 8 * 1024;
char buffer[buffer_size];
size_t length;
src = fopen(src_path, "rb");
dst = fopen(dst_path, "wb");
while (!feof(src))
{
length = fread(buffer, 1, buffer_size, src);
fwrite(buffer, 1, length, dst);
}
fclose(src);
fclose(dst);
}
解决方案
我相信您的问题是您正在将src
(这是指向主线程堆栈上的局部变量的指针)传递给线程的入口函数,但是由于您的copy()
函数在单独的线程中异步运行,因此char src[40]
您传递指针的数组在copy()
函数有机会读取其内容之前,已经从主线程的堆栈中弹出(并且可能被其他数据覆盖) 。
简单的解决方法是在堆上复制字符串,这样您就可以保证字符串在copy()
函数执行并读取它之前保持有效:
vth.emplace_back(std::bind(copy, "Original.deb", strdup(src)));
...并确保在使用copy()
完函数后释放堆分配:
void copy(const char *src_path, const char *dst_path)
{
FILE *src, *dst;
int buffer_size = 8 * 1024;
char buffer[buffer_size];
size_t length;
src = fopen(src_path, "rb");
dst = fopen(dst_path, "wb");
free(dst_path); // free the string previously allocated by strdup()
[...]
请注意,“Original.deb”参数目前没有相同的问题,因为“Original.deb”是字符串文字,因此静态存储在可执行文件中,这意味着只要程序是正在运行——但是如果/当您将代码更改为不为该参数使用字符串文字时,您可能也需要为它做类似的事情。
推荐阅读
- python - Django 模型 DateField 属性限制选择
- couchdb - 我可以使用值而不是键来查询视图吗?
- c# - 从百分比中删除小数点并在.net中保留百分比符号
- java - 将 targetSdkVersion 提高到 28 时,在路径上找不到类“com.google.android.gms.common.R$string”:DexPathList
- android - 为什么 Facebook 的 Unity SDK 没有将事件记录到分析?
- swift - 我打开了第二个视图,其中显示了集合中的一系列图像,我可以按下集合的图像以在第一个视图中使用图像吗?
- javascript - 如果付款成功或不成功,如何在重定向页面的顶部显示横幅
- c# - 团队中的 Bot 框架技能错误 - 有效域正确
- laravel - CSRF 令牌在 Laravel ajax 调用中不起作用
- docker - Docker System.Net.Http.HttpRequestException 上的 .netcore 微服务:无法分配请求的地址