#include <windows.h>
#include <stdio.h>
#include <time.h>
DWORD winapi Dohomework ( LPVOID p)
{
int i, j, sum = 0;
for (i = 0; I < 30000. i++)
{for
(j = 0; J < 30000; J +)
{
sum++;//Simulate the process of a person doing a job that takes a human (CPU) time
}
}
printf ("Sum is%d\n", sum);
return 0;
}
void Washclotheswithwashingmachine ()
{
int i;
for (i = 0; i < i++)
{
;//simulate the process of putting clothes into a washing machine, requiring a small amount of time (CPU) to sleep
(5000);//simulate washing process of washing machine, do not need person (CPU) spend time
}
int main ()
{
int t1, T2;
T1 = Clock ();
HANDLE hthread = CreateThread (null, 0, dohomework, NULL, 0, NULL);
Washclotheswithwashingmachine ();
CloseHandle (hthread);
t2 = Clock ();
printf ("Time is%d\n", t2-t1);
return 0;
}
The result is (multithreading):
Sum is 900000000
Time is 4999
If it is single-threaded, it is:
#include <windows.h>
#include <stdio.h>
#include <time.h>
void Dohomework ()
{
int I, j, sum = 0;
for (i = 0; I < 30000. i++)
{for
(j = 0; J < 30000; J +)
{
sum++;
}
}
printf ("Sum is%d\n", sum);
}
void Washclotheswithwashingmachine ()
{
int i;
for (i = 0; i < i++)
{
;
}
Sleep (5000);
}
int main ()
{
int t1, T2;
T1 = Clock ();
Washclotheswithwashingmachine ();
Dohomework ();
t2 = Clock ();
printf ("Time is%d\n", t2-t1);
return 0;
}
Results (single thread):
Sum is 900000000
Time is 8327
It is obvious that multithreading saves time because people are doing their homework at the same time when the washing machine washes clothes automatically.