提问人:laser_dude 提问时间:4/27/2022 更新时间:4/27/2022 访问量:57
C++ 中多对象多线程方法的比较
Comparison of methods for multithreading with multiple objects in C++
问:
我正在为一个“管理器”类处理 C++ 代码,该类在单独的线程中的多个成员对象中运行进程并返回一组值。我看到了实现这一点的三种基本方法:
- 使用相关对象的成员函数和返回值的回调机制创建每个线程;
- 在管理器类中提供一个辅助函数,该函数调用指定对象的成员函数,并使用此辅助函数创建单独的线程;或
- 使用相关对象的成员函数创建每个线程(如方法 #1 中所示),并将指针传递给变量以保存返回值。
我的问题是,在性能或其他因素方面,是否有令人信服的理由选择一种方法而不是另一种方法,同时牢记实际应用程序将具有不确定数量的对象的数组或向量(与以下示例不同)?
第一种方法的示例如下所示:
#include <thread>
#include <iostream>
#include <functional>
using namespace std;
using namespace std::placeholders;
typedef function<void(string, int)> Callback;
class Processor {
private:
string name;
Callback cb_func;
public:
Processor(string nme, Callback f) : name(nme), cb_func(f) { }
void do_stuff(int lim) { cb_func(name, rand() % lim); }
};
class Manager {
private:
Processor *p0, *p1;
public:
Manager() {
p0 = new Processor("lizard", std::bind(&Manager::report, this, _1, _2));
p1 = new Processor("ferret", std::bind(&Manager::report, this, _1, _2));
}
~Manager() {
delete p0;
delete p1;
}
void manage() {
thread t0 = thread(&Processor::do_stuff, p0, 100);
thread t1 = thread(&Processor::do_stuff, p1, 100);
t0.join();
t1.join();
}
void report(string source, int value) {
cout << source << " reports " << value << endl;
}
};
int main() {
Manager the_dude;
the_dude.manage();
return 0;
}
第二种方法的示例如下所示:
#include <thread>
#include <iostream>
using namespace std;
class Processor {
private:
string name;
public:
Processor(string nme) : name(nme) { }
int do_stuff(int lim) { return rand() % lim; }
string get_name() { return name; }
};
class Manager {
private:
Processor *p0, *p1;
public:
Manager() {
p0 = new Processor("lizard");
p1 = new Processor("ferret");
}
~Manager() {
delete p0;
delete p1;
}
void work(Processor *p, int lim) {
cout << p->get_name() << " reports " << p->do_stuff(lim) << endl;
}
void manage() {
thread t0 = thread(&Manager::work, this, p0, 100);
thread t1 = thread(&Manager::work, this, p1, 100);
t0.join();
t1.join();
}
};
int main() {
Manager the_dude;
the_dude.manage();
return 0;
}
第三种方法的示例如下所示:
#include <thread>
#include <iostream>
using namespace std;
class Processor {
private:
string name;
public:
Processor(string nme) : name(nme) { }
void do_stuff(int lim, string *nme, int *val) { *nme = name; *val = rand() % lim; }
};
class Manager
{
private:
Processor *p0, *p1;
string s0, s1;
int v0, v1;
public:
Manager() {
p0 = new Processor("lizard");
p1 = new Processor("ferret");
}
~Manager() {
delete p0;
delete p1;
}
void manage() {
thread t0 = thread(&Processor::do_stuff, p0, 100, &s0, &v0);
thread t1 = thread(&Processor::do_stuff, p1, 100, &s1, &v1);
t0.join();
t1.join();
report(s0, v0);
report(s1, v1);
}
void report(string source, int value) {
cout << source << " reports " << value << endl;
}
};
int main()
{
Manager the_dude;
the_dude.manage();
return 0;
}
答: 暂无答案
评论
std::future
可能会引起您的兴趣。new
p0
p1
Manager