我正在尝试翻译一些 C# 代码,它一次创建 N 个线程并在每个线程中运行一个函数。
我有两个问题:
-如何限制一次N个线程?
-当我在我的主要方法中引用静态整数 FastestMemory 和 SlowestMemory 时(当我在最后打印出值时),我的链接器似乎无法识别它们。
有人可以帮忙吗?
到目前为止我有:
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
class Test{
public:
static unsigned int FastestMemory;
static unsigned int SlowestMemory;
public:
Test(unsigned a, unsigned b){
FastestMemory = a;
SlowestMemory = b;
}
struct thread_data
{
int m_id;
thread_data(int id) : m_id(id) {}
};
static DWORD WINAPI thread_func(LPVOID lpParameter)
{
thread_data *td = (thread_data*)lpParameter;
int RepetitionNumber = td->m_id;
printf("thread with id = " + RepetitionNumber + '\n');
unsigned int start = clock();
vector<byte> list1;
vector<byte> list2;
vector<byte> list3;
for(int i=0; i<10000000; i++){
list1.push_back(57);
}
for (int i = 0; i < 20000000; i=i+2)
{
list2.push_back(56);
}
for (int i = 0; i < 10000000; i++)
{
byte temp = list1[i];
byte temp2 = list2[i];
list3.push_back(temp);
list2[i] = temp;
list1[i] = temp2;
}
unsigned int timetaken = clock()-start;
printf(RepetitionNumber + " Time taken in millisecs: " + timetaken);
if(timetaken < FastestMemory){
FastestMemory = timetaken;
}
if(timetaken > SlowestMemory){
SlowestMemory = timetaken;
}
return 0;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Test* t = new Test(2000000,0);
for (int i=0; i< 10; i++)
{
CreateThread(NULL, 0, Test::thread_func, new Test::thread_data(i) , 0, 0);
}
printf("Fastest iteration:" + Test::FastestMemory + '\n'); //Linker not recognising
printf("Slowest iteration:" + Test::SlowestMemory + '\n'); //Linker not recognising
int a;
cin >> a;
}
最佳答案
我不确定您所说的“一次限制 N 个线程”是什么意思。您的意思是您希望(例如)仅使用 5 个线程来执行问题中的 10 个任务吗?
如果是这样,您可能想要使用某种线程池。 Windows 有类似三个独立线程池 API 的东西,以及 I/O 完成端口,它们也可以充当线程池。如果您发现缺少线程池,也可以很容易地编写自己的线程池——但结构与您发布的有很大不同。
static unsigned int FastestMemory;
声明但不定义变量。您需要在类定义之外定义它:
class Test {
static unsigned int FastestMemory;
static unsigned int SlowestMemory;
// ...
};
unsigned int Test::FastestMemory = 0;
unsigned int Test::SlowestMemory = 0;
关于c++ - 节流 C++ 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9980040/