Do homework and wash clothes in multithreaded mode (the most popular and simple multithreaded example in history, no more and no explanation)

Source: Internet
Author: User
#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.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.