2

我正在尝试使用 pthreads 编写一个简单的 parallel_for。原始代码是这样的。

#ifdef HAVE_TBB
 template<typename Body> static inline
 void parallel_for( const BlockedRange& range, const Body& body )
 {
        tbb::parallel_for(range, body);
 }
#else
 template<typename Body> static inline
 void parallel_for( const BlockedRange& range, const Body& body )
 {      
        body(range); 
 }
#endif

我重写了 TBB 不存在的情况。这是我写的。我在编译它时遇到问题。当我在它之前写时,threadFunc 给出了错误template<typename Body>

In function 'void cv::parallel_for(const cv::BlockedRange&, const Body&)':
error: no matches converting function 'threadFunc' to type 'void* (*)(void*)'
error: candidates are: template<class Body> void* cv::threadFunc(void*)

这些是我收到的错误消息。可能必须有一个简单的修复。谢谢。

struct MyStruct {
    BlockedRange range;
    Body& body;
};

//template<typename Body>
static void* threadFunc(void *arg) {
    MyStruct<Body> *rangeBody = (MyStruct<Body>*) arg;
    rangeBody->body(rangeBody->range);
}

template<typename Body> static inline
void parallel_for( const BlockedRange& range, const Body& body )
{
    BlockedRange& range1 = BlockedRange(range.begin(), range.end()/2);
    BlockedRange& range2 = BlockedRange(range.end()/2, range.end());

    MyStruct<Body> rangeBody1; 
    rangeBody1.range = range1; 
    rangeBody1.body = body;

    MyStruct<Body> rangeBody2; 
    rangeBody2.range = range2; 
    rangeBody2.body = body;

    pthread_t thread1, thread2;
    pthread_create(&thread1, NULL, threadFunc, (void*) &rangeBody1);
    pthread_create(&thread2, NULL, threadFunc, (void*) &rangeBody2);
    pthread_join( thread1, NULL);
    pthread_join( thread2, NULL);    
}
4

1 回答 1

4

如果threadFunc是函数模板,则需要对其进行特化以获取所需的函数:

pthread_create(&thread1, NULL, threadFunc<Body>, &rangeBody1);
                                         ^^^^^^
于 2012-07-25T09:09:49.323 回答