目录:
Linux操作系统,C语言实现多线程
Windows操作系统,C语言实现多线程
Windows下的多线程(不带停止)
Linux操作系统,C语言实现多线程:
#include
#include
#include
void * ThreadOne ( void * threadArg )
{
printf ( "线程开始啦,参数是:%s\n" , (char *)threadArg );
return NULL;
}
int main ( void )
{
pthread_t ThreadID; /* 记录线程标识符 */
void * waitingResult; /* 等待线程退出的等待结果 */
int errorCode; /* 记录线程的错误代码 */
char * aMessage = "这是线程的参数" ;
/* 创建并启动线程ThreadOne。若返回值非零,则线程创建失败 */
errorCode = pthread_create( &ThreadID, NULL, ThreadOne, aMessage );
if ( errorCode != 0 )
{
printf ("线程ThreadOne创建失败。错误代码:%d\n", errorCode );
return EXIT_FAILURE ;
}
/* 等待线程标识符为的ThreadID的线程结束 */
errorCode = pthread_join( ThreadID, &waitingResult );
if ( errorCode != 0 )
{
printf ( "等待线程退出等待失败。错误代码:%d\n" , errorCode ) ;
return EXIT_FAILURE ;
}
printf( "线程的返回值是%p\n", waitingResult );
return EXIT_SUCCESS ;
}
Windows操作系统,C语言实现多线程:
#include
#include
DWORD APIENTRY ThreadOne ( LPVOID threadArg )
{
printf ( "线程开始啦,参数是:%s\n" , (char *)threadArg );
return 0;
}
int main ( void )
{
HANDLE hThread; /* 记录线程句柄 */
DWORD ThreadID; /* 记录线程ID号 */
DWORD waitingResult; /* 等待线程退出的等待结果 */
DWORD threadExitCode; /* 记录线程的返回值 */
char * aMessage = "这是线程的参数" ;
/* 创建并启动线程ThreadOne,返回值为线程句柄,赋值给hThread */
hThread = CreateThread ( NULL, 0L, ThreadOne, (LPVOID)aMessage, 0L, &ThreadID );
if ( hThread == NULL )
{
printf ("线程ThreadOne创建失败。错误代码:%lu\n", GetLastError() );
return EXIT_FAILURE ;
}
/* 等待线程句柄为的hThread线程结束 */
waitingResult = WaitForSingleObject ( hThread, INFINITE );
if ( waitingResult == WAIT_FAILED )
{
printf ( "等待线程退出等待失败。错误代码:%lu\n" , GetLastError() ) ;
return EXIT_FAILURE ;
}
if ( GetExitCodeThread ( hThread , &threadExitCode ) )
printf ( "线程的返回值是%lu\n", threadExitCode ) ;
else
printf ( "获取线程的返回值获取失败。错误代码:%lu\n" , GetLastError() ) ;
return EXIT_SUCCESS ;
}
Windows下的多线程:(不带停止)
#include
#include
DWORD WINAPI duoxianchen(LPVOID lpParam);
int main(int argc, char *argv[])
{
int num=0;
CreateThread(NULL,NULL,duoxianchen,&num,NULL, NULL);
while(1)
{
num++;
printf("主线程! %05d\n",nu***eep(40);
}
return 0;
}
DWORD WINAPI duoxianchen(LPVOID lpParam)
{
int* a=lpParam;
while(1)
{
++*a;
printf("副线程! %05d 0x%p\n",*a,a);
Sleep(80);
}
return 0;
}