<pre name="code" class="cpp">自己第一次涉及c语言的多线程编程,实属入门了解级别的;之前只做过java的Runnable的多线程编程。本次我们可以把屏幕看成是一个资源,这个资源被两个线程所共用,
/*
#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI Fun(LPVOID lpParamter)
{
while(1)
{
cout<<"Fun display!"<<endl;
Sleep(1000);// 1000 表示一秒
}
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
CloseHandle(hThread);
while(1)
{
cout<<"main display!"<<endl;
Sleep(2000);
}
return 0;
}// 出现连续多个空行或不换行问题
我们可以把屏幕看成是一个资源,这个资源被两个线程所共用,加入当Fun函数输出了Fun display!后,
//将要输出endl(也就是清空缓冲区并换行,在这里我们可以不用理解什么事缓冲区),但此时main函数
//确得到了运行的机会,此时Fun函数还没有来得及输出换行就把CPU让给了main函数,而这时main函数
//就直接在Fun display!后输出main display!
*/
// 解决方法一:
/*
#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI Fun(LPVOID lpParamter)
{
while(true)
{
cout << "Fun display!\n";
Sleep(1000);
}
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
CloseHandle(hThread);
while(true)
{
cout << "Main display!\n";
Sleep(2000);
}
return 0;
}
*/
// 解决方法二:实现交替运行,这次才是从根本上解决了问题,实现了多线程共享资源
/*
#include <iostream>
#include <windows.h>
using namespace std;
HANDLE hMutex;
DWORD WINAPI Fun(LPVOID lpParamter)
{
while(true)
{
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, "aa");
cout << hThread << " " << hMutex << endl;
CloseHandle(hThread);
while(true)
{
WaitForSingleObject(hMutex, INFINITE);
cout<<"main display!!!"<<endl;
Sleep(2000);
ReleaseMutex(hMutex);
}
return 0;
}原文地址:http://blog.csdn.net/u010700335/article/details/39557405