gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:27:18 25 4
gpt4 key购买 nike

我是 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);

Live Example

关于c++ - 以类对象和结构对象 c++ 开始线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37451054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com