Task queues are first-in-first-out queues that enable tasks to be delivered securely across multiple threads.
A task is an object that combines data and operations, which is defined as an object of the Ctask class.
Implementation of the task:
Task.cpp
#include "stdafx.h"
#include "Task.h"
#include <iostream>
using namespace std;
Ctask::ctask (int* ncount)
{
m_ncount = ncount;
}
Ctask::~ctask ()
{
}
void Ctask::D owork ()
{
(*m_ncount) + +;
cout << "Count =" << *m_ncount << Endl;
}
Task.h
#pragma once
class Ctask
{
int* m_ncount;
Public:
ctask (int* ncount);
~ctask ();
void DoWork ();
Implementation of queues:
TaskQueue.cpp
#include "stdafx.h" #include "TaskQueue.h" Ctaskqueue::ctaskqueue () {} ctaskqueue::~
Ctaskqueue () {}//worker thread void Ctaskqueue::workthread () {while (M_bisstart) {if (!m_taskqueue.empty ()) {
ctask* it = M_taskqueue.front ();
It->dowork ();
M_taskqueue.pop ();
Delete it;
Add a task to the task queue bool Ctaskqueue::P ush (ctask* Task) {if (task = nullptr) {return false;
} m_mutex.lock ();
M_taskqueue.push (Task);
M_mutex.unlock ();
return true;
///Get task from task queue ctask* ctaskqueue::P op () {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//Task queue
std::thread m_thread;
Std::mutex M_mutex;
BOOL M_bisstart; Whether the thread opens public
:
//worker-thread
void Workthread ();
Add task to Task queue
bool Push (ctask* Task);
Get tasks from task queue
ctask* pops ();
Open Thread
bool Start ();
Terminate thread
void Stop ();
Test Demo:
TaskQueue.cpp: Defines the entry point for a console application.
//
#include "stdafx.h"
#include "TaskQueue.h"
#include "Task.h"
void MyWorkTask1 (ctaskqueue* Ptaskqueue, int* ncount)
{for
(size_t i = 0; i < i++)
{
ctask* task = new Ctask (ncount);
Ptaskqueue->push (Task);
}
void MyWorkTask2 (ctaskqueue* ptaskqueue, int* ncount)
{for
(size_t i = 0; i < i++)
{
ctask* ta SK = 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);
Wait thread end
if (thread1.joinable ())
{
thread1.join ();
}
if (thread2.joinable ())
{
thread2.join ();
}
System ("pause");
return 0;
}
The above C + + simple task queue is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.