【问题标题】:Begin thread with class object and struct object c++使用类对象和结构对象c ++开始线程
【发布时间】:2016-05-26 03:27:21
【问题描述】:

我对 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 的构造函数采用指向Derived1 类的成员函数的指针,因此第二个参数需要是指向该类实例的指针(即, &amp;derived1 -- 和t2 线程类似)。

标签: c++ multithreading class data-structures derived-class


【解决方案1】:

您正在使用的std::thread 的构造函数采用指向成员函数的指针,因此第二个参数需要是类的实例,这是调用成员函数所必需的。

对于t1t2,第二个参数可以分别为&amp;derived&amp;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

【讨论】:

  • 詹姆斯·阿德基森,非常感谢。我已经坚持了很长一段时间。第二个修复成功了! :D
  • @acv17 太好了。由于您是新手,因此请记住对任何有用的答案进行投票,如果有正确答案,请接受。
猜你喜欢
  • 2021-03-10
  • 2014-10-30
  • 2013-11-17
  • 2021-04-04
  • 1970-01-01
  • 2020-10-03
  • 2010-09-15
  • 1970-01-01
  • 2014-05-14
相关资源
最近更新 更多