我能否通过将函数实现为类对象方法来避免使用互斥锁

Can I avoid using mutex lock by implementing function as a class object method

本文关键字:方法 对象 实现 函数      更新时间:2023-10-16

背景:我有一个位置的文件列表,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;
}

您能否也发布移动文件的内容以帮助您?谢谢。