可视化限制C++线程
visual Throttling C++ threads
我正在尝试翻译一些C#代码,它一次创建N个线程,并在每个线程中运行一个函数。
我有两个问题:
-如何一次限制N个线程?
-当我在主方法中引用静态int 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;
您正在声明而不是定义静态int。
尝试:
class Test{
public:
static unsigned int FastestMemory;
static unsigned int SlowestMemory;
// ...
};
unsigned int Test::FastestMemory = 0;
unsigned int Test::SlowestMemory = 0;
至于定义N个线程,请查看到目前为止的情况,尝试使用CreateThread
创建单独的线程并根据需要进行扩展。当然,这样做会给你一个非常基本的,可能不是很有用的线程模型。我建议阅读线程池。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?