C++11 Multithreading series The first part

Source: Internet
Author: User

Multithreaded programming for large programs, complex algorithms are widely used, has been developed under Windows, but the program needs to run in Linux and other systems, configuration boost standard library is also a solution, C++11 standard library implementation time is relatively long, most of the compiler today support, Therefore, using C++11 to achieve multithreading is undoubtedly the best choice.


According to Wikipedia: threads are the smallest unit in the operating system that can perform operational scheduling. It is included in the process and is the actual unit of operation in the process. A thread refers to a single sequence of control flows in a process in which multiple threads can be parallel, and each thread performs a different task in parallel. The SunOS is also known as the thread bit lightweight process, but the lightweight process is more a kernel thread, and the user thread becomes a thread. Multiple threads in the same process share all system resources in the process, such as virtual address spaces, file descriptors, and signal processing.


#include <iostream>
#include <thread>
void thread_id ()
{
	std::cout << thread ID = = "<< std::this_thread::get_id () << Std::endl;
}

int main ()
{
	std::thread td (THREAD_ID);
	Td.join ();
}


The execution body of a thread can be any callable object or function.

Call the addition function, call the function in the child thread from the main thread, and pass the argument:

#include <iostream>
#include <thread>
void thread_id (int a,int b)
{
	//std::cout << "Thread id = =" << std::this_thread::get_id () << Std::endl;
	Std::cout << A + b << std::endl;
}

int main ()
{
	std::thread td (thread_id,1,2);
	Td.join ();
}

The output result is 3.

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.