从类对象和结构对象 c++ 开始线程

Begin thread with class object and struct object c++

本文关键字:对象 开始 线程 c++ 结构      更新时间:2023-10-16

我对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的构造函数采用指向成员函数的指针,因此第二个参数必须是类的实例,这是调用成员函数所必需的。

t1t2的情况下,第二个参数可以分别是&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);

现场示例