我想翻译一些C#代码,它一次创建N个线程,并在每个线程中运行一个函数。节流C++线程
我有两个问题:
- 我该如何限制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;
}
嗨杰里,是的,我的意思是5个线程执行10个任务(因此大致执行两次线程迭代)。 – mezamorphic 2012-04-02 16:37:10
@ user1107474:在这种情况下,您需要一个线程池。基本思想是创建一个[线程安全队列](http://stackoverflow.com/questions/2375132/releasesemaphore-does-not-release-the-semaphore/2375370#2375370)。将你的'thread_data'放入main中的队列中。你的线程函数重复从队列中检索一个项目,处理它,然后检索另一个(该问题有一些示例代码显示了总体思路)。 – 2012-04-02 16:41:25