C++ ¼òµ¥µÄÈÎÎñ¶ÓÁÐÏê½â。本站提示廣大學習愛好者:(C++ ¼òµ¥µÄÈÎÎñ¶ÓÁÐÏê½â)文章只能為提供參考,不一定能成為您想要的結果。以下是C++ ¼òµ¥µÄÈÎÎñ¶ÓÁÐÏê½â正文
ÈÎÎñ¶ÓÁÐÊÇÖ¸Äܹ»ÊµÏÖÈÎÎñÔÚ¶àÏ̼߳䰲ȫ´«µÝµÄÏÈÈëÏȳöµÄ¶ÓÁС£
ÈÎÎñÊÇÖ¸×éºÏÁËÊý¾ÝºÍ²Ù×÷µÄ¶ÔÏó£¬ÕâÀïÃ涨ÒåΪCTaskÀàµÄ¶ÔÏó¡£
ÈÎÎñµÄʵÏÖ£º
Task.cpp
#include "stdafx.h" #include "Task.h" #include <iostream> using namespace std; CTask::CTask(int* nCount) { m_nCount = nCount; } CTask::~CTask() { } void CTask::DoWork() { (*m_nCount)++; cout << "Count = " << *m_nCount << endl; }
Task.h
#pragma once class CTask { int* m_nCount; public: CTask(int* nCount); ~CTask(); void DoWork(); };
¶ÓÁеÄʵÏÖ£º
TaskQueue.cpp
#include "stdafx.h" #include "TaskQueue.h" CTaskQueue::CTaskQueue() { } CTaskQueue::~CTaskQueue() { } //¹¤×÷Ïß³Ì void CTaskQueue::WorkThread() { while (m_bIsStart) { if (!m_taskQueue.empty()) { CTask* it = m_taskQueue.front(); it->DoWork(); m_taskQueue.pop(); delete it; } } } //ÏòÈÎÎñ¶ÓÁÐÌí¼ÓÈÎÎñ bool CTaskQueue::Push(CTask* task) { if (task == nullptr) { return false; } m_mutex.lock(); m_taskQueue.push(task); m_mutex.unlock(); return true; } //´ÓÈÎÎñ¶ÓÁлñÈ¡ÈÎÎñ CTask* CTaskQueue::Pop() { CTask* it = nullptr; m_mutex.lock(); if (!m_taskQueue.empty()) { it = m_taskQueue.front(); m_taskQueue.pop(); } m_mutex.unlock(); return it; } bool CTaskQueue::Start() { if (m_bIsStart) { return false; } m_bIsStart = true; m_thread = std::thread(&CTaskQueue::WorkThread, this); return true; } void CTaskQueue::Stop() { m_bIsStart = false; m_thread.join(); }
TaskQueue.h
#pragma once #include "Task.h" #include <queue> #include <mutex> #include <thread> class CTaskQueue { public: CTaskQueue(); ~CTaskQueue(); private: std::queue<CTask*> m_taskQueue; //ÈÎÎñ¶ÓÁÐ std::thread m_thread; std::mutex m_mutex; bool m_bIsStart; //Ïß³ÌÊÇ·ñ¿ªÆô public: //¹¤×÷Ïß³Ì void WorkThread(); //ÏòÈÎÎñ¶ÓÁÐÌí¼ÓÈÎÎñ bool Push(CTask* task); //´ÓÈÎÎñ¶ÓÁлñÈ¡ÈÎÎñ CTask* Pop(); //¿ªÆôÏß³Ì bool Start(); //ÖÕÖ¹Ïß³Ì void Stop(); };
²âÊÔdemo£º
// TaskQueue.cpp : ¶¨Òå¿ØÖÆ̨ӦÓóÌÐòµÄÈë¿Úµã¡£ // #include "stdafx.h" #include "TaskQueue.h" #include "Task.h" void MyWorkTask1(CTaskQueue* pTaskQueue, int* nCount) { for (size_t i = 0; i < 20; i++) { CTask* task = new CTask(nCount); pTaskQueue->Push(task); } } void MyWorkTask2(CTaskQueue* pTaskQueue, int* nCount) { for (size_t i = 0; i < 20; i++) { CTask* task = new CTask(nCount); pTaskQueue->Push(task); } } int _tmain(int argc, _TCHAR* argv[]) { CTaskQueue* pTaskQueue = new CTaskQueue(); pTaskQueue->Start(); int* nCount = new int(0); std::thread thread1(&MyWorkTask1, pTaskQueue, nCount); std::thread thread2(&MyWorkTask2, pTaskQueue, nCount); //µÈ´ýÏ߳̽áÊø if (thread1.joinable()) { thread1.join(); } if (thread2.joinable()) { thread2.join(); } system("pause"); return 0; }
ÒÔÉÏÕâƪC++ ¼òµ¥µÄÈÎÎñ¶ÓÁÐÏê½â¾ÍÊÇС±à·ÖÏí¸ø´ó¼ÒµÄÈ«²¿ÄÚÈÝÁË£¬Ï£ÍûÄܸø´ó¼ÒÒ»¸ö²Î¿¼£¬Ò²Ï£Íû´ó¼Ò¶à¶àÖ§³Ö½Å±¾Ö®¼Ò¡£