可视化限制C++线程

visual Throttling C++ threads

本文关键字:线程 C++ 可视化      更新时间:2023-10-16

我正在尝试翻译一些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创建单独的线程并根据需要进行扩展。当然,这样做会给你一个非常基本的,可能不是很有用的线程模型。我建议阅读线程池。