从类对象和结构对象 c++ 开始线程
Begin thread with class object and struct object c++
我对c ++很陌生,我真的不知道如何克服这个问题。本质上,我有一个包含 2 个派生类的基类。我有第四个"处理"类。
我需要创建三个线程,其中两个派生类生成数据,"处理"类基于这些数据进行自己的计算。
我希望两个派生类将结果放在一个结构中,并且处理类访问该结构。
我遇到麻烦的地方是在启动线程时,因为我需要为它提供派生类的对象和数据结构的对象,但它只是不起作用。这或多或少是我所拥有的。
#include <cstdio>
#include <iostream>
#include <random>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <chrono>
#include <ctime>
#define _USE_MATH_DEFINES
#include <math.h>
#include <time.h>
#include <iostream>
#include <thread>
#include <atomic>
#include <vector>
#include <mutex>
using namespace std;
struct Test_S
{
vector<double> test_vector1;
vector<double> test_vector2;
mutex test_mtx;
};
class Base
{
public:
Base();
void domath() {cout<<"base function"<<endl;}
int i;
};
class Derived1 : public Base
{
public:
Derived1();
void domath1()const {test_s.test_vector1.push_back(1);}
};
class Derived2 : public Base
{
public:
Derived2();
void domath2()const {test_s.test_vector2.push_back(2);}
};
int main( int argc, char ** argv )
{
Base base;
Derived1 derived1;
Derived2 derived2;
Test_S test_s;
std::thread t1(&Derived1::domath1, &test_s);
std::thread t2(&Derived2::domath2, &test_s);
t1.join();
t2.join();
}
您使用的
std::thread
的构造函数采用指向成员函数的指针,因此第二个参数必须是类的实例,这是调用成员函数所必需的。
在t1
和t2
的情况下,第二个参数可以分别是&derived
和&derived2
。
关于传递给std::thread
的函数所使用的test_s
,你需要一种方法来将该状态传递给这些类。您可以将状态作为参数传递给传递给 std::thread
的函数。
仅供说明:
void domath1(Test_S* test_s) const { test_s->test_vector1.push_back(1); }
...
std::thread t1(&Derived1::domath1, &derived1, &test_s);
现场示例
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- 从类对象和结构对象 c++ 开始线程
- 对象的向量(如何开始)
- 如果文件在构造函数中不存在,则抛出异常,并在 main() 中创建对象时尝试/捕获它,如果好 - 开始使用该对象
- 有没有办法从任意点开始在 Phonon 媒体对象中启动流
- 当我们开始覆盖内存时,对象的生命周期是否已经结束?
- 是否重用存储开始新对象的生存期
- 从3d对象开始