我用VC控制台写多线程的例子
#include<iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI fun1proc(LPVOID lpparameter);
int index=0;
int main()
{
while (index++<1000)
{
HANDLE hthread1;
hthread1=CreateThread(NULL,0,fun1proc,NULL,0,NULL);
CloseHandle(hthread1);
cout<<"主线程运行"<<endl;
Sleep(3000);
}
return 0;
}
DWORD WINAPI fun1proc(LPVOID lpparameter)
{
cout<<"线程1运行"<<endl;
return 0;
}
就是这个了 最简单的多线程 但是输出的却是一些乱码 但是写别的控制台程序没有乱码 觉得VC6的安装应该没有问题,请问哪位大大知道为什么!!!
#include<iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI fun1proc(LPVOID lpparameter);
int index=0;
int main()
{
while (index++<1000)
{
HANDLE hthread1;
hthread1=CreateThread(NULL,0,fun1proc,NULL,0,NULL);
CloseHandle(hthread1);
cout<<"主线程运行"<<endl;
Sleep(3000);
}
return 0;
}
DWORD WINAPI fun1proc(LPVOID lpparameter)
{
cout<<"线程1运行"<<endl;
return 0;
}
就是这个了 最简单的多线程 但是输出的却是一些乱码 但是写别的控制台程序没有乱码 觉得VC6的安装应该没有问题,请问哪位大大知道为什么!!!
如果把Sleep(3000);这条语句放在cout<<"主线程运行"<<endl;之前的话就不会再出现那个问题。
多线程的程序中,对于这些多个线程都会用的变量,一般都需要增加保护.
可以使用CriticalSection, Mutex等.
CRITICAL_SECTION CriticalSection; void main()
{
... // Initialize the critical section one time only.
if (!InitializeCriticalSectionAndSpinCount(&CriticalSection, 0x80000400) )
return;
... // Release resources used by the critical section object.
DeleteCriticalSection(&CriticalSection)
}DWORD WINAPI ThreadProc( LPVOID lpParameter )
{
... // Request ownership of the critical section.
EnterCriticalSection(&CriticalSection); // Access the shared resource.
cout < <"线程1运行" < <endl; // Release ownership of the critical section.
LeaveCriticalSection(&CriticalSection); ...
}注意设置编译选项为多线程!