我能否通过将函数实现为类对象方法来避免使用互斥锁
Can I avoid using mutex lock by implementing function as a class object method
背景:我有一个位置的文件列表,moveFile()
函数将用于移动这些文件。 我的目标是并行移动所有这些文件。所以,我实现了多个线程。
为了避免冲突,最初我在moveFile()
之前考虑了互斥锁。这将阻止线程并行运行。
以下是它的实现方式:
std::mutex mtx;
enum class status
{ SUCCESS, FAILED };
status moveFile()
{ //function implementation }
void fileOperator()
{ // This is prevent parallel operation
mtx.lock;
moveFile();
mtx.unlock;
}
int main ()
{
int threadSize= 3; //generic size
std::thread fileProc[threadSize];
int index = 0;
// staring new threads
for (index; index < threadSize; index++)
{
fileProc[index] = std::thread (&fileOperator);
}
//joining all the threads
for (int i=0; i <threadSize; i++)
{
fileProc[i].join();
}
return 0;
}
建议:我想知道,如果我删除互斥锁,像在类中一样实现moveFile()
并将其作为对象方法调用,它会是实现并行操作的更好方法吗?
不太确定这里的问题是什么,很可能它位于 moveFile 函数中,但这样的东西应该可以工作:
#include <future>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
std::mutex mtx;
enum class status { SUCCESS, FAILED };
status moveFile() {
std::cout << "Moving file" << std::endl;
return status::SUCCESS;
}
void fileOperator() {
std::lock_guard<std::mutex> lock(mtx);
moveFile();
}
int main(int argc, char** argv) {
std::vector<std::thread> threads;
int threadSize = 3;
for (int index = 0; index < threadSize; ++index) {
threads.push_back(std::thread(&fileOperator));
}
for (auto& th : threads) {
th.join();
}
return 0;
}
您能否也发布移动文件的内容以帮助您?谢谢。
相关文章:
- 使用std::函数映射对象方法
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 有没有一种方法可以使用placement new将堆叠对象分配给分配的内存
- 从父类方法返回子类对象
- 在他自己的方法中,有可能将一个对象取消引用到另一个对象吗
- 为什么此派生对象无法访问基类的后递减方法?
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 正在调用shared_ptr对象方法
- 将方法转换为调用该方法的成员函子对象会导致崩溃
- 检查哪个对象调用了另一个对象的对象方法
- CPU 瓶颈;处理具有许多非静态对象的 3D 场景渲染的简单方法
- 直接在 unordered_map 的方法中使用哈希,而不是生成哈希的用户定义对象
- 没有取消引用/解包对象的标准方法?
- 使用 gmock c++ 在真实对象上调用方法
- 当我调用对象的方法时,对象的成员会发生变化
- 根据对象类调用不同的方法
- 如何在C++中循环访问未知对象方法?
- 使用动态实例化的对象填充矢量的快速方法
- 对类中的对象使用方法