在程序运行中,主程序会创建线程,线程会按自己的方式单独运行,主程序创建线程后,不等线程结束,就运行后面的程序,当运行到程序的最后,结束程序,同时,强行结束线程的运行,这一点与JAVA不同,JAVA语言会等待线程的结束.
下面有一个例子,表示了这种关系,线程中打开一个,SALARY.DAT文件,并对文件写,以测试,程序结束,线程运行到哪里.
#include <windows.h>
#include <iostream.h>
#include <fstream.h>
const char* salary_file="SALARY.DAT";
ifstream input_file;
ofstream output_file;
int code;
char name[16];
float salary;
float total;
int loop;
DWORD WINAPI Fun1Proc(LPVOID lpParameter);//thread data
DWORD WINAPI Fun2Proc(LPVOID lpParameter);//thread data
int index=0;
int tickets=10;
HANDLE hMutex;
void func();
void main()
{
cout<<" func run!"<<endl;
func();
cout<<" fun instance can stop!"<<endl;
int tmp=tickets;
while(tmp>0)
tmp=tickets;
}
void func()
{
HANDLE hThread1;
HANDLE hThread2;
//创建线程
hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);
hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
//创建互斥对象
hMutex=CreateMutex(NULL,TRUE,"tickets");
if (hMutex)
{
if (ERROR_ALREADY_EXISTS==GetLastError())
{
cout<<"only one instance can run!"<<endl;
return;
}
}
WaitForSingleObject(hMutex,INFINITE);
ReleaseMutex(hMutex);
ReleaseMutex(hMutex);
cout<<" one instance can run!"<<endl;
//Sleep(10);
cout<<" one instance can run!"<<endl;
}
//线程1的入口函数
DWORD WINAPI Fun1Proc(LPVOID lpParameter)//thread data
{
while (true)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,INFINITE);
if (tickets>0)
{
Sleep(1);
cout<<"thread1 sell ticket :"<<tickets--<<endl;
output_file.open(salary_file);
if(!output_file){
cout<<"Can 1 not open salary file!"<<endl;
;}
cout<<"Can 1 open salary file!"<<endl;
output_file<<4793<<" "<<"Leeman"<<" "<<tickets<<endl;
output_file<<4793<<" "<<"Jumbo"<<" "<<650.50<<endl;
output_file.close();
// AfxMessageBox("synchro Thread ");
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
//线程2的入口函数
DWORD WINAPI Fun2Proc(LPVOID lpParameter)//thread data
{
while (true)
{
ReleaseMutex(hMutex);
WaitForSingleObject(hMutex,INFINITE);
if (tickets>0)
{
Sleep(1);
cout<<"thread2 sell ticket :"<<tickets--<<endl;
output_file.open(salary_file);
if(!output_file){
cout<<"Can 1 not open salary file!"<<endl;
;}
cout<<"Can 2 open salary file!"<<endl;
output_file<<4793<<" "<<"Leeman"<<" "<<725.50<<endl;
output_file<<4793<<" "<<"Jumbo"<<" "<<650.50<<endl;
output_file<<4793<<" "<<"Jumdo"<<" "<<tickets<<endl;
output_file.close();
}
else
break;
ReleaseMutex(hMutex);
}
return 0;
}
线程会随主程序的,不同结束时刻,输出不同的值,表示主程序结束时,线程运行到哪里.