您的位置:首页 > 编程语言

学习学习多线程编程,落入俗套。

2013-10-26 00:36 162 查看
写点多线程编程的程序吧,无论是后端还是什么都需要编写多线程程序的。我也来一个Threadpool落入俗套。

后天会把程序贴出来,未完待续。

HANDLE CreateThread(

LPSECURITY_ATTRIBUTES lpThreadAttributes, // SD

SIZE_T dwStackSize, // initial stack size

LPTHREAD_START_ROUTINE lpStartAddress, // thread function

LPVOID lpParameter, // thread argument

DWORD dwCreationFlags, // creation option

LPDWORD lpThreadId // thread identifier

);//参数
先写一个最简单的多线程 程序,记录一下线程的生成和执行。

#include <iostream>

#include <windows.h>

using namespace std;



DWORD WINAPI Fun(LPVOID lpParamter)

{

while(1) { cout<<"Fun display!\n"; Sleep(1000);}

}



int main()

{

HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);

CloseHandle(hThread);

while(1) { cout<<"main display!\n"; Sleep(2000);}

return 0;

}

增加Mutex加锁机制之后:

#include <iostream>

#include <windows.h>

using namespace std;

HANDLE hMutex;

DWORD WINAPI Fun(LPVOID lpParamter)

{



while(1) {

WaitForSingleObject(hMutex, INFINITE);

cout<<"Fun display!"<<endl;

Sleep(1000);

ReleaseMutex(hMutex);

}

}



int main()

{

HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);

hMutex = CreateMutex(NULL, FALSE, "screen");

CloseHandle(hThread);

while(1) {

WaitForSingleObject(hMutex, INFINITE);

cout<<"main display!"<<endl;

Sleep(2000);

ReleaseMutex(hMutex);

}

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: