我对我的一个项目做了一个快速总结,其中我有两个线程应该能够读写一个公共变量(在实际项目中由互斥锁保护)。
我不明白这个错误
这两个线程理论上是由主线程启动的这个主线程是对象的一个函数,它的作用是管理这个对象的子线程。我不知道这是否可能
main.cpp
#include <thread>
#include "Object.h"
using namespace std;
int main(){
Object tmp;
tmp.ChangeSetting(42);
thread mainthread(&Object::MainTread, &tmp);
mainthread.join();
}
Object.h
#ifndef SRC_OBJECT_H_
#define SRC_OBJECT_H_
#include <thread>
#include <iostream>
using namespace std;
class Object {
private:
int stupidvalue;
void subThread1();
void subThread2();
public:
void MainTread();
void ChangeSetting(int psvalue);
Object();
virtual ~Object();
};
#endif /* SRC_OBJECT_H_ */
Object.cpp
#include "Object.h"
void Object::subThread1(){
cout << "subthread1";
}
void Object::subThread2(){
cout << "subthread2";
}
void Object::MainTread(){
thread tmp1(subThread1);
thread tmp2(subThread2);
tmp1.join();
tmp2.join();
}
Object::Object() {
stupidvalue = 0;
}
void Object::ChangeSetting(int psvalue){
stupidvalue = psvalue;
}
Object::~Object() {
}
和my error
Info: Internal Builder is used for build
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\main.o" "..\src\main.cpp"
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o "src\Object.o" "..\src\Object.cpp"
In file included from ..srcObject.h:5,
from ..srcObject.cpp:2:
C:/msys64/mingw32/include/c++/10.2.0/thread: In instantiation of 'std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (Object::*)(); _Args = {}; <template-parameter-1-3> = void]':
..srcObject.cpp:13:24: required from here
C:/msys64/mingw32/include/c++/10.2.0/thread:136:44: error: static assertion failed: std::thread arguments must be invocable after conversion to rvalues
136 | typename decay<_Args>::type...>::value,
| ^~~~~
10:26:25 Build Failed. 1 errors, 0 warnings. (took 1s.304ms)
我读到可能是输入错误,但是没有参数。
subThread1
和subThread2
也是成员函数。你需要使用指针到成员函数的语法,就像你在main()
void Object::MainTread(){
thread tmp1(&Object::subThread1, this);
thread tmp2(&Object::subThread2, this);
tmp1.join();
tmp2.join();
}
或者像其他答案建议的那样使用lambda
您正在传递没有对象本身的非静态方法:
thread tmp1(subThread1); //error: subThread() cannot be invoked without object
你可以写一个lambda:
// passing this to lambda ok solong the object itself outlives the lambda ...
// in your case ok because joining in place.
thread tmp1([this]() { this->subThread(); });
否则如果线程可以超过对象,您通常会创建一个共享指针(这样,对象将通过shared_pointer至少与线程本身一样长):
thread tmp1([self=this->shared_from_this()]() { self->subThread(); });
要做到这一点,Object需要从std::enable_shared_from_this<Object>:
class Object : public std::enable_shared_from_this<Object> {...}