Thread-safe, C ++ multi-threaded management (detach, join, get_id)

Thread-safe
thread-safe function: When a function is called repeatedly by multiple concurrent threads, its result is always correct

General thread unsafe situation, due to the global process of different threads of the same process memory space shared / static storage area and the heap, if a function contains global variables and static variables, it may be thread-safe, leading to a program error . But if the operation of the global variables and static variables are only read, not modified, then this function can also be seen as thread-safe.


Multi-threaded C ++ (C ++ 11)

Multithreading demo

C ++ 11 standard library, providing multi-threaded library, you need to  #include <thread> header files (mainly provides classes for thread management std::thread)

#include <iostream>
#include <thread>
using namespace std;

void output(int i){
	cout << i << endl;
}

int main(){
	for(uint8_t i = 0; i < 8; i++)	{
		thread th(output, i);
		th.detach();	//detach表示该线程可以在后台运行,无需等待当前线程完成,会继续执行后面的操作
	}
	getchar();
	
	return 0;
}

Output:

You can not see the program in order from 1 to 8 outputs, and not behind each number has a line feed.

Analysis:
Creating the eight processes, each process calls the output method, output of the two-step process: ① print out the value of i, ② print wrap.

Issues related to multithreaded core: resource competition.

8-core CPU created eight threads, but only one console, and at the same time, only one thread owns the only console.

So there will be circumstances: After a thread consumes console digital print, not enough time to print new line, the situation on the console is occupied by another process.

Two kinds of C ++ 11 threads waiting for the end of the way:

detach way to start the thread independent running in the background, continue down the current code, without waiting for the end of the process. Create a new process of concurrent execution.
join mode , will block the current code, we need to wait for the start of the current thread execution is completed, will continue to the next step.

Use demo before join modify

#include <iostream>
#include <thread>
#include <sstream>
using namespace std;

void output(int i){
	cout << i << endl;
}

int main(){
	stringstream ss;
	for(int i = 0; i < 8; i++)	{
		thread th(output, i);
		ss << "(" << th.get_id() << "): ";	//通过get_id获取线程的id 
		cout << ss.str();
		ss.str("");	//释放ss的缓冲区 
		th.join();
	}
	
	return 0;
}

Results are as follows:

To make the current thread is finished by using join, blocking the way, the next thread begins execution again.

发布了5 篇原创文章 · 获赞 0 · 访问量 1080

Guess you like

Origin blog.csdn.net/sinat_18811413/article/details/104101967