相关疑难解决方法(0)

Windows API线程池简单示例

[编辑:感谢MSalters的回答和Raymond Chen对InterlockedIncrement与EnterCriticalSection/counter ++/LeaveCriticalSection的回答,问题解决了,下面的代码工作正常.这应该提供一个有趣的简单示例,在Windows中使用线程池]

我无法找到以下任务的简单示例.例如,我的程序需要将一个巨大的std :: vector中的值递增一,所以我想并行执行.它需要在程序的整个生命周期中多次执行此操作.我知道如何在每次调用例程时使用CreateThread,但我没有设法使用ThreadPool去掉CreateThread.

这是我做的:

class Thread {
public:
    Thread(){}
    virtual void run() = 0 ; // I can inherit an "IncrementVectorThread"
};
class IncrementVectorThread: public Thread {
public:
   IncrementVectorThread(int threadID, int nbThreads, std::vector<int> &vec) : id(threadID), nb(nbThreads), myvec(vec) { };

   virtual void run() {
        for (int i=(myvec.size()*id)/nb; i<(myvec.size()*(id+1))/nb; i++)
          myvec[i]++; //and let's assume myvec is properly sized
    }
   int id, nb;
   std::vector<int> &myvec;
};

class ThreadGroup : public std::vector<Thread*> {
public:
    ThreadGroup() { 
         pool = …
Run Code Online (Sandbox Code Playgroud)

c++ windows multithreading threadpool

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

c++ ×1

multithreading ×1

threadpool ×1

windows ×1