【发布时间】: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类的成员函数的指针,因此第二个参数需要是指向该类实例的指针(即,&derived1-- 和t2线程类似)。
标签: c++ multithreading class data-structures derived-class