【发布时间】: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