[英]How to start a thread from one object's method by calling another method?
我閱讀了有關 C++ 線程的各種文章,其中包括GeeksForGeeks文章。 我也讀過這個問題,但這些都不能滿足我的需要。 在我的項目中(這里太復雜了,無法提及),我需要一些類似的東西:
#include <iostream>
#include <thread>
using namespace std;
class Simulate{
public:
int Numbers[100][100];
thread Threads[100][100];
// Method to be passed to thread - in the same way as function pointer?
void DoOperation(int i, int j) {
Numbers[i][j] = i + j;
}
// Method to start the thread from
void Update(){
// Start executing threads
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
Threads[i][j] = thread(DoOperation, i, j);
}
}
// Wait till all of the threads finish
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
if (Threads[i][j].joinable()) {
Threads[i][j].join();
}
}
}
}
};
int main()
{
Simulate sim;
sim.Update();
}
請問我該怎么做? 任何幫助表示贊賞,並歡迎替代解決方案。 我是一名受過訓練的數學家,學習 C++ 不到一周,所以更喜歡簡單。 我迫切需要一些類似的東西來加快我的研究模擬。
調用成員函數和傳遞參數的最簡單方法是使用lambda 表達式:
Threads[i][j] = std::thread([this, i, j](){ this->DoOperation(i, j); });
[]
中列出的變量被捕獲,它們的值可以被{}
的代碼使用。 lambda 本身具有唯一的匿名類型,但可以隱式轉換為std::thread
構造std::function
接受的std::thread
std::function
。
但是,在大多數系統上,啟動 100x100 = 10000 個線程會很快耗盡內存。 添加比 CPU 內核更多的線程並不會提高計算任務的性能。 相反,最好啟動例如 10 個線程,每個線程在循環中處理 1000 個項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.