KMThreadPool: 3 – Thread Pool Step 1: Utilities, Locks and Algorithms

3 – Thread Pool Step 1:Utilities, Locks and Algorithms

Utilities:

We’re going to set up some classes and type definitions for use through-out the thread pool. These will be our utility objects, stored in thekmp::threading::utility namespace. For this project, we only have 2 objects in our Utility namespace: a function pointer type defined as KMTaskFunc and an abstractbase class entitled IKMTaskData. Lets have a look:

namespace utility
{
         //Class Interfaces
         class IKMTaskData
         {
         public:
                  IKMTaskData() {}
                  IKMTaskData(const IKMTaskData&) {}
                  IKMTaskData& operator = (const IKMTaskData&) {}
                  virtual ~IKMTaskData() = 0 {};
         };
 
         //Type Definitions
         typedef void (*KMTaskFunc)(IKMTaskData*);
 
}

These 2 objects are actually the heart of the thread pool, believe it or not (if you don’t: OK, fine, enjoy your busted thread pool). Here is an overview on how theKMTaskFunc and IKMTaskData work inside the thread pool.

KMTaskFunc

This function pointer is going tobe the task we want to put on another thread. You can define this functionanywhere inside your program* – the thread pool itself will beset up to accept a function pointer to send to the threads.

The task function pointer we’veset up here is returning void. You could have it return another value, but youwould need to set up a way to get that value back from the threads, which ispretty tedious, so we’ll stick to the basics. The only parameter is a pointerto the ABC IKMTaskData.

IKMTaskData

A problem with threading is thepassing of data, especially shared data. Because of paralellism, threads thatshare a variable could modify it or access it at the same time (as I’ve said onpage 2). A method around this is to give the thread classes local storage ofthe data they need to complete the task, filled out with data from the exactmoment they were created that won’t be modified by other threads (meaning:avoid using pointers).

To do this effectively, we haveour IKMTaskData. When you’re developing you tasks, you’ll create child classes the derivefrom this ABC, Adding in members and such that your task will need, to passalong to the threads. When sending this task to the thread pool, the pool willcast your class to the IKMTaskData. Inside or your task, you’ll cast it back to yourchild object, and grab all the yummy data goodness you loaded into it. Simple.

* Note: If your task function pointer is a member function inside a class, it won’twork; the function must be static in order to work correctly. A method aroundthis is to create a static member function in your class, and in your childIKMTaskData class, have a pointer to this. Inside that static function, youwould call the task you wanted to multithread.

Example:

First, create the task child object, addingwhatever members you’ll need.

class taskData : IKMTaskData
{
 public:
 A* ptr_A;
 int _a;
 int _b;
 ...
 ...
}

Define our class, with the task that gets calledby the thread, and the task that does the actual work.

class A
{
 void task(int a, int b)
 {
  //Do Stuff...
 }
 static void STATIC_TASK(IKMTaskData* data)
 {
  taskData* myData = (taskData*)data;
  A* myClass = myData->ptr_A;
  myClass->task(myData->_a, myData->_b);
 }
 ...
 ...
}

Then, somewhere inside of class A…

...
...
pthreadpool->AddTask(STATIC_TASK, new taskData(this, 100, 6));
...
...

Locking

KMLock

Locking is one of the morepowerful tools we have when developing multithreaded applications, but it’s alsoa double-edged sword when abused. Locking, in terms of threading, preventsother threads from running a segment of code while it’s “locked” and will blockall other threads until the segment is Unlocked. That’s very helpful if youhave sensitive data that should only be modified by one thread at a time…

But it can slow you down. How?Think about it: you’re blocking the other threads from processing code(assuming other threads want to process the same code all at once). You createa bottle neck. However, if you keep the segment small enough, and don’t uselocks like a madman, you’ll be fine. In the event that you make a game to thescale of Crysisor World of Warcraft, and you’re locking so muchyour game is moving at 6 FPS, then you may want to consider looking intolockless algorithms (and, I warn you, locklessness is a pain).

So here’s a glimpse at the KMLock class we use in the thread pool.

class KMLock
{
private:
         CRITICAL_SECTION m_critsec;
public:
         KMLock()
         {
                  ::InitializeCriticalSection(&m_critsec);
         }
         ~KMLock()
         {
                  ::DeleteCriticalSection(&m_critsec);
         }
         void Lock()
         {
                  ::EnterCriticalSection(&m_critsec);
         }
         void Unlock()
         {
                  ::LeaveCriticalSection(&m_critsec);
         }
protected:
};

For the locks, we’re just usingWindows Critical Sections (maybe one day I’ll change it touse a more cross-platform implemntation, but for now that is fine). Use thisclass wisely and sparingly; don’t lock what doesn’t need to be.

Algorithms

KMQueue

To make this simple: *SPOILERALERT!* our Thread Pool class is going to contain a task queue. Once one ourthreads goes idle, it will check the task queue, and pop off the next task andrun it. That’s how the heart beats in our thread pool (unless you’re the guywho chose to be the “nonbeliever” earlier).

So why did I make a queue? I usedCritical Sections earlier, and Windows has the STD library!

Let me tell you something: thecurrent C++ STD library isn’t thread-safe (but the STD library coming in C++0xis); there’s no locking, nocompare-and-swaps – nothing.That’s why I’ve researched what’s called aTwo-LockQueue by Maged M. Michael and MichaelL. Scott. You can find the PDF they wrote on it here for more information->1996PODC Queues. I’m going to just run down the quick-and-dirty basics withyou.

Our problem here is we’ll have atime when one thread will try modifying the queue while another thread is.They’ll run into problems like trying to delete data while another thread isaccessing it, or theABA problem. Our simplistic solution requires just 2locks and a false head.

Our queue is comprised of nodes.The nodes are simple: a templated TYPE for the item in the node, and a nextpointer. Our queue has 4 members: a head node pointer, a tail node pointer, aKMLock for the head, and a KMLock for the tail.

In the constructor, we create ourfirst node. Why? This node is going to be a dummy node. A problem occurs when 2threads try to access the same data. One thread can delete the data while theother thread thinks the data is still valid. The other thread tries to use thedeleted data and BAM! Zombie thread. So what we do is we use the head pointeras an “invalidation data container.” When we callpop() on the queue, instead of popping off thehead and returning the data from the head, we get the data from the heads’next, then pop the head and move the heads next into the head position.Confusing, but by doing this, we allow for the possiblity for 2 threads to tryto access the head. So if one thread gets the head while another is accessingit, the head in the queue is moved to an invalidation container instead ofgetting totally deleted, so both values are still valid. The heads get deletedon the next pop. (If you still don’t get it (and I don’t blame you) read thewhitepaper a few times and look at the code. You’ll facepalm once you get it).

The locks are simple tounderstand in their logic. They’re just there so one thread can be pushingwhile another thread is popping. both provide protection to their specifiednodes so no 2 threads can try topush() or pop() at the same time.

Then there’s the empty() function, which checks if the queue isempty. if the head node has a next, the queue is not empty. If it’s just thehead, then it is (remember, the head is just an invalid dummy). This is themost exciting function in the whole project. Not.

 

转自:http://keithmaggio.wordpress.com/code/c-win32-thread-pool-manager/3-step1/

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
### 回答1: :xv6是一个基于Unix的操作系统,它是一个教学用途的操作系统,旨在教授操作系统的基本概念和实现。它是在MIT的x86架构上开发的,包括了Unix的一些基本功能,如进程管理、文件系统、内存管理等。xv6的源代码是公开的,可以用于学习和研究。 Unix utilities是Unix操作系统中的一些基本工具,如ls、cd、cp、mv、rm等。这些工具可以帮助用户管理文件和目录,执行各种操作。这些工具的实现是基于Unix的系统调用,可以通过编写C程序来调用这些系统调用实现相应的功能。这些工具是Unix操作系统的基础,也是其他操作系统的参考。 ### 回答2: lab: xv6 and unix utilities 实验是一项旨在帮助学生深入理解操作系统和 Unix 工具使用的实验。该实验分为两个部分,第一部分教授学生如何构建和运行 xv6 操作系统;第二部分则重点教授 Unix 工具的使用。 在 xv6 操作系统部分,学生将学习到操作系统内核的基本结构和实现原理。实验将引导学生理解内存管理、进程调度、系统调用等关键操作系统概念。此外,学生还将学习如何编写简单的 shell 以及如何通过修改 xv6 内核代码来实现新的系统调用和功能。 在 Unix 工具部分,学生将探索 Unix 系统中广泛使用的常见工具。这些工具包括 vi 编辑器、grep、awk、sed 等。实验将介绍这些工具的基本使用方法以及它们在处理文本和数据时的实际应用。这部分实验还将让学生深入了解 shell 和 shell 脚本的编写,帮助他们在 Unix 环境中轻松地编写脚本和自动化任务。 lab: xv6 and unix utilities 实验对计算机科学专业的学生具有重要意义。通过完成这个实验,学生将建立起对操作系统和 Unix 工具的深入理解,为他们成为一名优秀的软件工程师奠定坚实的基础。同时,这个实验还将为学生提供实践经验,让他们能够将所学知识应用到真实的软件开发和运维中。 ### 回答3: Lab: xv6 and Unix Utilities是一个计算机科学领域的实验,旨在让学生深入了解Unix操作系统以及操作系统本身的自我管理机制。在这个实验中,学生需要从零开始构建一个类似于Unix的操作系统,在这个操作系统中,学生需要设计一些基本命令,例如ls,cat,grep等等,并且将它们与系统的底层API结合起来,以实现各种功能。此外,学生还需要了解和探索xv6这个开发工具,它是一个轻量级基于Unix的操作系统实现,具有一定的可移植性和简洁性,因此,它可以作为一个基础框架来实现一个完整的Unix操作系统。 这个实验的目标是让学生了解Unix的基本命令结构和API,以及操作系统内部的一些基本机制,例如进程管理,文件系统交互以及进程通信等等。此外,通过实现这些命令,学生还可以学到一些基本的C语言编程技能,例如文件操作,字符串处理以及进程管理等等。还可以学习到如何使用Git等版本控制工具,以及如何进行调试和测试代码的技巧。 在整个实验过程中,学生需要有较强的自我管理能力和综合运用能力,因为在实现这些命令的同时,他们还需要和其他团队成员进行交流和合作,以及不断改进和完善他们的代码。总之,这个实验是一个非常有趣且富有挑战性的计算机科学课程,通过完成这个实验,学生可以更好地了解操作系统的构造和运作机制,以及如何设计和开发高效的系统级应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值