不懂c++建立多线程的工作原理
只知道多线程是,好几个工作,先执行一点这个,再执行一点那个...
不知道是具体来说是用什么方法来先执行一点这个,再执行一点那个的
这儿有一代码,麻烦哪位同学能一行一行地解释一下:
#define WIN32_LEAN_AND_MEAN // make sure certain headers are included correctly
#include <windows.h>
#include <windowsx.h>
#include <conio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <math.h>
#include <io.h>
#include <fcntl.h>
DWORD WINAPI Printer_Thread(LPVOID data);
DWORD WINAPI Printer_Thread(LPVOID data)
{
for (int index=0; index <25; index++)
{
printf( "%d ",data);
Sleep(100);
}
return((DWORD)data);
}
void main(void)
{
HANDLE thread_handle; // this is the handle to the thread
DWORD thread_id; // this is the id of the thread
printf( "\nStarting threads...\n ");
thread_handle = CreateThread(
NULL,
0,
Printer_Thread, (LPVOID)1,
0,
&thread_id);
for (int index=0; index <50; index++)
{
printf( "2 ");
Sleep(100);
}
CloseHandle(thread_handle);
printf( "\nAll threads terminated.\n ");
} // end main
[解决办法]
看操作系统原理,有讲述多线程的工作原理
[解决办法]
因为cpu以线程为单位分配时间片,对所有的线程进行时间片的轮转
这样比如现在两个进程在跑,进程a呢两个线程a1,a2,
进程b呢是你的程序,一个线程b1,这样的话,你抢到的时间片为1/3,一分钟之内你的程序cpu只跑了20sec,你多线程那就抢的执行机会多嘛,基本原理如此
okokok
不懂c++建立多线程的工作原理,该如何解决
不懂c++建立多线程的工作原理只知道多线程是,好几个工作,先执行一点这个,再执行一点那个...不知道是具体来
