多线程 简单例子 windows ------(一)
线程创建CreateThread()、【建议MS运行时库api _beginthreadex()】
HANDLE WINAPI CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, //线程安全相关的属性,常置为NULL
SIZE_T dwStackSize, //新线程的初始化栈在大小,可设置为0
LPTHREAD_START_ROUTINE lpStartAddress, //被线程执行的回调函数,也称为线程函数
LPVOID lpParameter, //传入线程函数的参数,不需传递参数时为NULL
DWORD dwCreationFlags, //控制线程创建的标志 立即执行or暂时挂起
LPDWORD lpThreadId //传出参数,用于获得线程ID,如果为NULL则不返回线程ID
);
创建A,B两个线程,然后打印ThreadDemo类里面的名字以及数量,加了锁
按照顺序打印,若未同步则乱序。
多线程使用过程需要注意,线程安全。
#include <iostream>
#include <stdlib.h>
#include <windows.h>
#include <string.h>
#include <vector>
#include <mutex>
#include <process.h>
using namespace std;
#define MY_GUID "040fb37a-b2e1-494e-aa4e-c0044b2b767c"
//线程同步问题【线程同步】
#define NAME_LENGTH 40
HANDLE g_hMutex = NULL; //互斥量
class ThreadDemo{
public:
ThreadDemo():nMaxNum(0) {
strcpy_s(strThreadName,strlen(strThreadName),"");
}
int nMaxNum;
char strThreadName[NAME_LENGTH];
};
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
DWORD error = 0;
ThreadDemo *pThreadData = static_cast<ThreadDemo*> (lpParameter);
for (int i = 0; i < pThreadData->nMaxNum; ++i)
{
error = WaitForSingleObject(g_hMutex, INFINITE);//无限等待这个锁,等到了执行,等不到不执行下面的
//可以从error判断是否等到了
cout << pThreadData->strThreadName << ": " << i << endl;
Sleep(100);
//释放互斥量锁
ReleaseMutex(g_hMutex);
}
return 0;
}
int main(int argc, char *argv[])
{
//创建一个互斥量
g_hMutex = CreateMutex(NULL, FALSE, MY_GUID);
ThreadDemo threadData, threadIndex;
threadData.nMaxNum = 5;
strcpy_s(threadData.strThreadName, _countof(threadData.strThreadName),"Thread_1");
threadIndex.nMaxNum = 10;
strcpy_s(threadIndex.strThreadName, _countof(threadIndex.strThreadName), "Thread_2");
HANDLE DataThread = CreateThread(NULL, 0,ThreadProc, &threadData, 0, NULL);
HANDLE IndexThread = CreateThread(NULL, 0, ThreadProc, &threadIndex, 0, NULL);
CloseHandle(DataThread);
CloseHandle(IndexThread);
for (int num = 0; num < 10; ++num) {
WaitForSingleObject(g_hMutex, INFINITE);//无限等待这个锁,等到了执行,等不到不执行下面的
cout << "main thread is: " << num << endl;
Sleep(100);
//释放互斥量锁
ReleaseMutex(g_hMutex);
}
system("pause");
return 0;
}