将Windows 多线程API封装成一个类XThread,
//XThread.h
#pragma once
#ifdef XPLATFORM_EXPORTS
#define XPLATFORM_API __declspec(dllexport)
#else
#define XPLATFORM_API __declspec(dllimport)
#endif
class XPLATFORM_API XThread
{
public:
bool Start();
void Wait();
void Suspend();
void Resume();
virtual void Main() = 0;
XThread();
~XThread();
private:
unsigned int thread_handler = 0;
};
//XThread.cpp
#include "stdafx.h"
#include "XThread.h"
#include <process.h>
#include <windows.h> //只是在cpp中引用
//万一外部有相同的函数名不产生冲突,只在本cpp中有效。
static void ThreadMain(void *para)
{
XThread *th = (XThread *)para;
th->Main();
_endthread();
}
XThread::XThread()
{
}
XThread::~XThread()
{
}
bool XThread::Start()
{
thread_handler = _beginthread(ThreadMain, 0, this);
//直接把this指针传过去,那么就可以访问成员函数了
if ((int)thread_handler <= 0)
{
return false;
}
return true;
}
void XThread::Wait()
{
if (thread_handler == 0) return;
WaitForSingleObject((HANDLE)thread_handler, INFINITE);
}
void XThread::Suspend()
{
if (thread_handler == 0) return;
SuspendThread(HANDLE(thread_handler));
}
void XThread::Resume()
{
if (thread_handler == 0) return;
ResumeThread(HANDLE(thread_handler));
}
使用XThread类:
#include <iostream>
#include "XThread.h"
#include "windows.h"
using namespace std;
static char buffer[1024] = { 0 };
class Mythread :public XThread
{
public :
void Main()
{
for (;;)
{
int size = sizeof(buffer);
for (int i = 0; i < size; i++)
{
buffer[i] = c;
}
buffer[size - 1] = '\0';
cout <<'['<< buffer<<']'<<endl;
Sleep(500);
}
}
char c;
};
int main()
{
Mythread s1;
Mythread s2;
s1.c = 'A';
s2.c = 'B';
s1.Start();
s2.Start();
getchar();
return 0;
}
项目工程源代码:https://download.youkuaiyun.com/download/qq_26272885/10519717