#pragma once
#include
HANDLE threadHandle;
DWORD WINAPI ThreadProc( LPVOID lpParameter )
{
//该线程做的事情为:备咐求iA+iB的和(如果你有什么代码要你创建的线程运行的话,就将代码添加在这里)
int iA,iB;
iA = 5;
iB = 6;
int iSum = iA+iB;
//终止线程
TerminateThread( threadHandle, 0 );
return 0;
}
int main()
{
//创建线程(创建线程后,线程函数会自动调用)
threadHandle = CreateThread( NULL, //一般为NULL
0, /颂滚巧/一般为0
ThreadProc, //线程函数(自动调用野键)
NULL, //一般为NULL
0, //一般为0
NULL //
);
system( "pause" );
}
简单的多线程编程
Linux系统下的多线程遵循POSIX线程接口,称为pthread。枝扰宴编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux下pthread的实现是通过系统调用clone()来实现的。clone()是Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看猛银有关文档说明。下面我们展示一个最简单的多线程程序example1.c。
/* example.c*/
#include
#include
void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
}
int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0){
printf ("Create pthread error!\n");
exit (1);
}
for(i=0;i<3;i++)
printf("This is the main process.\n");
pthread_join(id,NULL);
return (0);
}
我们编译此程序:
gcc example1.c -lpthread -o example1
运行example1,我们得到如下结果:
This is the main process.
This is a pthread.
This is the main process.
This is the main process.
This is a pthread.
This is a pthread.
再次运行,我们可能得到如李肢下结果:
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
This is a pthread.
This is the main process.
忘采纳