C ++ Concurrency and multithreading study notes - the basic concept and realization

  • basic concepts
    • Complicated by
    • Executable programs, processes, threads
    • Learning experience
  • Concurrent implementation
    • More complicated process
    • Multithreading
    • to sum up
  • C ++ Standard Library

 

basic concepts

(Concurrent, processes, threads)
to distinguish between primary C ++ programming and senior programming

Complicated by

Two or more tasks simultaneously: a program to perform multiple tasks at the same time, among these tasks are independent of each other, the previous single-core CPU computer only when certain moment can only perform one task.

Microscopic serial, parallel, macroscopically

1. Single-core CPU operating system scheduling, task switching per second, looks like multi-tasking at the same time, in fact, by switching from. Resources needed between different tasks is not the same, when switching of the need to preserve some of the variables, switch back again when you need to recover some of the value of the variable (time overhead, space overhead) the more, the greater the overhead of task - context switching.

2. The multi-core CPU (multi-processor computer), a server and high performance computing. Or individual PC multi-core CPU, truly multi-task at the same time, the number of tasks is less than auditing, true parallel execution.

Concurrent use purpose: to complete multiple tasks simultaneously and improve performance.

Executable programs, processes and threads

System files, such as exe file in the window, or ls la, rwx, Executive authority under linxu file - an executable program.

Process is the basic unit of resource allocation, usually an executable process is a process.

After 1) to create, it is a process. 

2) Each process has a main thread, the main thread only.

In fact, when the process of running the program is the main thread to perform the main function of the code, the main function is finished, turn off the main thread, the main thread of the same life cycle and processes.

In fact, the implementation of the code is thread ==> (OS) thread is the basic unit of resource scheduling. "The implementation of the road code."

Outside the main thread, other threads can be created by writing code yourself, other threads to run another program.

 

Note: The thread is not possible, each thread requires a physical space, and context switching process comes at a price, to save a lot of intermediate states, too many threads, most of the time to switch on the thread, this will consume the procedural time running, if the thread more to a certain extent, operating efficiency is not high.

 

 

The actual environment, you need multiple threads scenario:

 Player 1: recharge

 Player 2: draw card

Player 1 use - recharge thread -> change the database, Player 2 -> draw card thread -> change the database.

Before the next mission after the current thread processing tasks. . . Process threads to provide services to the client.

to sum up

1. thread to execute the code.

2. Thread a piece of code execution path, and a new thread represents a new path.

3. The process of automatically includes a main thread. The main thread with the process starts, creating multiple encoded by other threads: non-main thread, but the number is not recommended to create a maximum of more than 200 to 300, a context switch time-consuming, the actual project tuning, sometimes occupy too much context switching no sense of time.

4. The main thread automatically starts a process at least one thread - the main thread.

5. multithreaded programs - different threads to provide different services, high operating efficiency, and in the end how high are difficult to quantify. The actual project experience and optimization.

Concurrent implementation

multi-Progress

After the software is to open a process.

Account server and game logic server interaction: the exchange of data through the port.

socket servers on different computers

Multithreading

Single process, creates multiple threads, each with its own independent operational path, but a process all threads share address space (shared memory). Global variables, pointers, references, can be passed between threads, so: using multi-threaded multi-process far less than the cost.

C ++ Standard Library

thread

class thread;

Thread

Class to represent individual threads of execution.

A thread of execution is a sequence of instructions that can be executed concurrently with other such sequences in multithreading environments,
while sharing a same address space.

  An initialized thread object represents an active thread of execution; Such a thread object is joinable, and has a unique thread id.

  A default-constructed (non-initialized) thread object is not joinable, and its thread id is common for all non-joinable threads.

   A joinable thread becomes not joinable if moved from, or if either join or detach are called on them.

 

example:

Execute functions:

void my_print() 
{
	cout << "my thread start\n";
	for (int i = 0; i < 1000; ++i);
	cout << "my thread end\n" << endl;
}

  

#include <the Thread> 
#include <iostream> 

a using namespace std; 
int main () 
{ 
	
	
	// If you want to keep the code to create their own thread created, the main thread to keep running. There are exceptions 
    std :: cout << "! The Hello World \ the n-"; 
	// A) contains a header file 
	// b) create a function 
	// c) main start writing code in 
	the Thread myThread1 (my_print); 
	the Thread myThread2 (my_print ); 
	myThread1.join (); 
	
	myThread2.join (); 

	COUT << "the Main the Thread" << endl; 
	return 0;

join()

void join();
Join thread

The function returns when the thread execution has completed.

This synchronizes the moment this function returns with the completion of all the operations in the thread: This blocks the execution of the thread that calls this function until the function called on construction returns (if it hasn't yet).

After a call to this function, the thread object becomes non-joinable and can be destroyed safely.

join represents block the main thread, the main thread waits for the child thread is finished, then thread and then start to go down.

The main thread to go down, when faced with myThread1.join () in the main thread waits for the child thread myThread1, when the child thread is finished, the convergence process, the main thread continue to go down.

1) block the main thread and wait for the child thread is finished.

2) If the child thread is not finished, the main thread ends, the program is unstable! ! !

 

 

 

detach()

detach (): the main thread does not wait for the child threads. Traditional multi-threading to create a lot of sub-thread, the main thread-by-thread waiting for the end of the child, this programming method is not very good, so the introduction of the detach (). The main thread and the child thread does not converge, sub-thread system went backstage, it was taken over by the equivalent of C ++ run-time, when the child thread is finished, the runtime library is responsible for cleaning up the process by the relevant resources.

void detach();
Detach thread

Detaches the thread represented by the object from the calling thread, allowing them to execute independently from each other.

Both threads continue without blocking nor synchronizing in any way. Note that when either one ends execution, its resources are released.

After a call to this function, the thread object becomes non-joinable and can be destroyed safely.

Linux: presence of background ==> daemon threads, not by the current thread execution

    :: cout << std "! the Hello World \ the n-"; 
	// A) contains a header file 
	// b) create a function 
	// c) main start writing code in 
	the Thread myThread1 (my_print, '1'); 
	the Thread myThread2 (my_print,, '2'); 
	myThread1.detach (); 
	myThread2.detach (); 
	COUT << "the Main the Thread" << endl;

 ? ? ? Into the background yet ????? in the main thread and finally add a while (1); see complete results

1) detach () function is executed in the background

2) to exit the main thread, the child thread will quit

3) detach () puts the thread to lose control of our own

 

 

 Therefore, the child thread the main thread and other normally. Can no longer join once detach (), the most common is to control the life cycle of the thread.

joinable()

To determine whether you can successfully use the join () or detach (), when the complexity of the code, need to use.

bool joinable() const noexcept;
Check if joinable

Returns whether the thread object is joinable.

thread object is joinable if it represents a thread of execution.

thread object is not joinable in any of these cases:

Other ways to create a thread

A callable object constructor by

class MyThread {
public:
	void operator()() //不能带参数
	{
		cout << "my thread start\n";


		cout << "my thread end\n" << endl;
	}
};

  

//类对象的写法

	MyThread obj;
	thread myThread(obj);
	myThread.join();

 如果要传参用如下的写法构造

class MyThread {
public:
	int& m_i;
	MyThread(int& i) :m_i(i) {}
	void operator()() 
	{
		cout << "my thread start\n";

		cout << "m_i的值为" << m_i << endl;

		cout << "my thread end\n" << endl;
	}
};

  注意这个例子:如果用detach()后台执行线程obj,主线程和MyThread 的对象obj的运行路径分开,但是参数m_i是主线程按照引用的方式传给obj的,所以会产生如下情况:如果主线程运行结束,会释放变量,那么最后结果中,分离的线程obj会调用一个不存在的变量,运行错误。

        主线程执行完之后,构造的对象也会被销毁?为什么使用类没有问题?一旦调用了detach(),那么主线程执行结束了,可调用对象也能执行。因为用了detach()之后把对象复制到线程中,主线程销毁后,复制的对象依然存在,所以没有引用,或者指向这些局部变量的指针,就不会产生问题。===>对象是被复制到线程中去。可以写一个拷贝构造函数,看一下结果。

参考文献

https://study.163.com/course/courseLearn.htm?courseId=1006067356&from=study#/learn/video?lessonId=1053452413&courseId=1006067356

http://www.cplusplus.com/reference/thread/thread/

Guess you like

Origin www.cnblogs.com/rynerlute/p/11788273.html