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