c++ - 我可以通过将函数实现为类对象方法来避免使用互斥锁吗

标签 c++ multithreading c++11 locking mutex

背景: 我有一个位置中的文件列表和用于移动这些文件的 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;
}

您能否也请发布 moveFile 的内容以便能够帮助您?谢谢。

关于c++ - 我可以通过将函数实现为类对象方法来避免使用互斥锁吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756116/

相关文章:

c++ - “下一个”不是 'std' 的成员

java - 如何在方法和线程之间共享字符串?

android - 为什么AsyncTask的doInBackground()中不能使用Context

c++ - 如何判断 C++ 模板类型是否为 C 样式字符串

c++ - C++11 是否允许在 lambda 内部和 lambda 内部进行以下嵌套可变参数扩展?

c++ - 在C++中定义带有函数参数的结构体方法

c++ - 用户定义的文字是在编译时还是运行时解析的?

c++ - C/C++ 中 MySQL 的静态链接

c# - IAsyncResult 的 WaitHandle 和阻塞?

c++ - 具有大值跨度的 double 组求和 : proper algorithm