这里是什么,我试图做一个简化版本:创建一个类来存储线程,并美其名曰
#include <iostream>
#include <vector>
#include <thread>
#include <atomic>
class client {
private:
std::vector<std::thread> threads;
std::atomic<bool> running;
void main() {
while(running) {
std::cout << "main" << std::endl;
}
}
void render() {
while(running) {
std::cout << "render" << std::endl;
}
}
public:
client() {
running = true;
threads.push_back(std::thread(&client::main, this));
threads.push_back(std::thread(&client::render, this));
}
~client() {
running = false;
for(auto& th : threads) th.join();
};
};
int main() {
client c;
std::string inputString;
getline(std::cin, inputString);
return 0;
}
(注:代码已经改变,因为问题是书面)
我想要做的是创建一个持有主循环(类的)线程,渲染和其他一些事情的类。但是,我无法获得这个简化版本的工作。我曾尝试使用互斥锁来锁定和解锁线程,但似乎没有任何帮助。我不知道它为什么不起作用,但我怀疑这是在threads.push_back(std::thread(this->main, this));
中使用this
的结果。
代码的当前结构不必保留...唯一的要求是使用它自己的成员函数之一作为线程(并且该线程存储在类中)。我不确定这是否需要两门课程,或者如果我在一门课程中尝试这样做是正确的。我见过很多创建对象的例子,然后调用创建线程的成员。我试图避免这种情况,而是在构造函数中创建线程。
你在运行这个吗?使用GCC,我甚至无法编译程序,它抱怨将'this-> main'和'this-> render'传递给''thread'构造函数,因为*“非法使用非静态成员函数”*。 – Dolda2000
@ Dolda2000 MinGW-W64-builds-4.3.0 – Brandon