【问题标题】:Can I avoid using mutex lock by implementing function as a class object method我可以通过将函数实现为类对象方法来避免使用互斥锁吗
【发布时间】:2018-08-08 21:48:21
【问题描述】:

背景:我有一个位置中的文件列表和将用于移动这些文件的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() 做了什么才能让您知道它是否安全。
  • 不,如果您有多个线程读取和写入同一个资源,那么该资源是否是一个类并不重要——您将需要某种锁。此外,std::thread fileProc[threadSize]; 不是有效的 C++。
  • @Neil Butterworth 在这种情况下我还有其他选项可以并行处理文件吗?
  • 如果fileOperator 所做的只是对moveFile 的同步调用,那么您的程序将不会有太多的并行性。查看moveFile 内部以查看实际共享资源的访问位置,并保护这些访问。
  • 您可能根本不需要互斥锁,但从您发布的代码中无法判断。

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


【解决方案1】:

不太确定这里的问题是什么,很可能它位于 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 的内容以帮助您解决这个问题?谢谢。

【讨论】:

  • 很遗憾,我无权访问 moveFile 的内容。如果我能得到帮助,我会发布。
  • 这与所讨论的代码相同,您在这里不提供任何答案。如果你想问moveFile的内容,你应该刚刚发表评论。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 2012-05-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多