c++多线程

来源:互联网 发布:知果网络科技有限公司 编辑:程序博客网 时间:2024/05/21 18:03
// xiancheng.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <windows.h>
#include <iostream>


using namespace std;

DWORD WINAPI Fun(LPVOID lpParamter)
{
while (1){ 
cout << "Fun" << endl; 
Sleep(1000); 
}
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
CloseHandle(hThread);
while (1){ 
cout << "main" << endl; Sleep(2000); 
}
return 0;

}

此程序定义了一个多线程的程序,但是输出结果有时候是两个换行,有时候没有换行,原因是因为执行cout<<"Fun"之后,可能资源被剥夺走了,没有执行end;

c++利用Mutex实现了线程同步问题


// xiancheng.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <windows.h>
#include <iostream>


using namespace std;


HANDLE hMutex;
DWORD WINAPI Fun(LPVOID lpParamter)
{
while (1){
WaitForSingleObject(hMutex, INFINITE);
cout << "Fun" << endl;
Sleep(1000);
ReleaseMutex(hMutex);
}
}
int main()
{
HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL);
hMutex = CreateMutex(NULL, FALSE, NULL);
CloseHandle(hThread);
while (1){
WaitForSingleObject(hMutex, INFINITE);
cout << "main" << endl; Sleep(2000);
ReleaseMutex(hMutex);
}
return 0;
}

解决了刚才的问题

createMutex()创建了一个进程

WaitForSingleObject创建了一个自己所有的线程,执行期间,别人不能使用资源

ReleaseMutes,释放刚才所创建的资源

0 0
原创粉丝点击