这是我正在玩的一个玩具示例,用于学习如何使用 TBB。Parallel::operator() 应该并行运行,但它有一个关键区域,一次只能由一个处理器访问,因此它打印的消息不会被打乱。我的问题是它无法编译并且编译器消息并没有真正帮助我。我究竟做错了什么?
此外,这是否被认为是在 parallel_for 中实现互斥锁的正确方法?
#include <iostream>
#include <vector>
#include <cmath>
#include <tbb/tbb.h>
typedef tbb::queuing_mutex Mutex;
struct Parallel
{
Mutex mutex;
std::vector<int> * values;
Parallel(std::vector<int> * values_) : values(values_) {}
void operator()( tbb::blocked_range< unsigned int > & range ) const {
for(unsigned int i = range.begin(); i < range.end(); ++i) {
{
Mutex::scoped_lock lock(mutex);
if ( (*values)[i] > 40)
{
std::cout << "NO SCRAMBLING ALLOWED!\n";
std::cout.flush();
}
lock.release();
}
}
}
};
int main() {
const int someValue = 20000;
std::vector<int> data(someValue);
for(int i = 0; i < someValue; ++i) {
data[i] = std::rand();
}
tbb::parallel_for( tbb::blocked_range<unsigned int>(0, data.size()),
Parallel(&data) );
}
贝娄是错误信息:
/path-to-src/main.cpp: In member function 'void Parallel::operator()(tbb::blocked_range<unsigned int>&) const':
/path-to-src/main.cpp:20:46: error: no matching function for call to 'tbb::queuing_mutex::scoped_lock::scoped_lock(const Mutex&)'
/path-to-src/main.cpp:20:46: note: candidates are:
In file included from /usr/include/tbb/tbb.h:65:0,
from /path-to-src/main.cpp:4:
/usr/include/tbb/queuing_mutex.h:80:9: note: tbb::queuing_mutex::scoped_lock::scoped_lock(tbb::queuing_mutex&)
/usr/include/tbb/queuing_mutex.h:80:9: note: no known conversion for argument 1 from 'const Mutex {aka const tbb::queuing_mutex}' to 'tbb::queuing_mutex&'
/usr/include/tbb/queuing_mutex.h:77:9: note: tbb::queuing_mutex::scoped_lock::scoped_lock()
/usr/include/tbb/queuing_mutex.h:77:9: note: candidate expects 0 arguments, 1 provided
/usr/include/tbb/queuing_mutex.h:66:11: note: tbb::queuing_mutex::scoped_lock::scoped_lock(const tbb::queuing_mutex::scoped_lock&)
/usr/include/tbb/queuing_mutex.h:66:11: note: no known conversion for argument 1 from 'const Mutex {aka const tbb::queuing_mutex}' to 'const tbb::queuing_mutex::scoped_lock&'