簡體   English   中英

C++ 中的線程錯誤“靜態斷言失敗”

[英]Error of threads in C++ "static assertion failed"

我快速總結了一個項目,其中我有兩個線程應該能夠讀取和寫入一個公共變量(在實際項目中受互斥鎖保護。

我不明白這個錯誤

這兩個線程理論上是由一個主線程啟動的這個主線程是object的一個function,它的作用是管理這個object的子線程。我不知道這是否可能

主.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() {
}

和我的錯誤

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 ..\src\Object.h:5,
                 from ..\src\Object.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]':
..\src\Object.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)

我讀到這可能是打字錯誤,但沒有參數。

subThread1subThread2也是成員函數。 您需要像在main()中那樣使用指向成員函數的語法

void Object::MainTread(){
    thread tmp1(&Object::subThread1, this);
    thread tmp2(&Object::subThread2, this);

    tmp1.join();
    tmp2.join();

}

或者像其他答案建議的那樣使用 lambda。

您正在傳遞沒有 object 本身的非靜態方法:

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(); }); 

否則,如果線程可以比 object 長壽,您通常會創建一個共享指針(這樣 object 將至少與線程本身一樣長地通過 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> {...}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM