2017-12-13 7 views
0

Qt Creator에서 C++을 사용하여 다른 클래스에서 동일한 함수를 여러 번 호출해야합니다. 그러나 이로 인해 전반적인 성능 속도가 느려집니다. 따라서 실시간 작업을 수행하기 위해 멀티 스레딩을 사용하려고 생각했습니다. 일부 검색 후 Qt Concurrent이 도움이 될 수 있으므로 다음 단계를 시도해보십시오.Qt Concurrent : 다른 클래스의 멤버 함수 호출

내 목표 기능이 클래스에 있습니다

std::vector<float> mvec; 
// here put some values into mvec; 
std::string mstring = "test"; 

myClass mcl; 

QFuture<float> f1 = QtConcurrent::run(mcl.foo(mvec, mstring)); 
f1.waitForFinished(); 

그러나이 말하는 오류를 제공합니다 :

Class myClass 
{ 
    public foo(std::vector<float> inputVec, std::string inputStr); 
} 

그리고 내 메인 클래스에서, 나는 이렇게

no matching function for call to 'run(float)' 
'functor' cannot be used as a function 
'float' is not a class, struct, or union type 
... 

나는 또한 std::thread을 다음과 같이 사용하려고 시도했다 :

std::thread t1 = std::thread(mcl.foo, mvec, mstring); 
if(t1.joinable()) t1.join(); 

그러나 이것은 다음과 같은 오류가 발생이 :

invalid use of non-static member function 

나는 온라인으로 여전히 혼란 많은 예제 코드를 시도했습니다. 이 코드를 원활하게 실행하고 스레드로부터 안전하게 보호하려면 어떻게해야합니까? 고맙습니다.

답변

2

다음 명령문의 foo 방법을 실행하고 run 기능에 그것의 결과를 전달 같은

QtConcurrent::run() also accepts pointers to member functions. The first argument must be either a const reference or a pointer to an instance of the class. Passing by const reference is useful when calling const member functions; passing by pointer is useful for calling non-const member functions that modify the instance.

For example, calling QByteArray::split() (a const member function) in a separate thread is done like this:

// call 'QList<QByteArray> QByteArray::split(char sep) const' in a 
separate thread QByteArray bytearray = "hello world"; 
QFuture<QList<QByteArray> > future = QtConcurrent::run(bytearray, &QByteArray::split, ','); 
... 
QList<QByteArray> result = future.result(); 

이 따라서, 여러분의 코드가 아니라 보여야 다음 documentation에서보세요.

QtConcurrent::run(mcl.foo(mvec, mstring)); 

올바른 형식은 다음과 같습니다

QtConcurrent::run(&mcl, &myClass::foo, mvec, mstring); 

또한 그 이후 f1.waitForFinished();, 실제로 블록을 호출 스레드가 foo 방법이 완료 될 때까지 있습니다. 따라서 멀티 스레딩의 이점을 얻지 못할 것입니다.

+0

대단히 고마워요, 효과가있었습니다! –

2

방금 ​​호출 한 결과가 아니라 (구성원) 함수 자체에 더하여 (구성원과 관련된 객체를 더하여) 전달해야합니다.

myClass mcl; 

QFuture<float> f1 = QtConcurrent::run(&mcl, &myClass::foo, mvec, mstring); 
f1.waitForFinished(); 
+0

답장을 보내 주셔서 감사합니다. –