c++11~c++20 -05-thread_local

一、thread_local简介

      thread_local变量是C++ 11新引入的一种存储类型。它会影响变量的存储周期(Storage duration),被thread_local声明的变量在行为上非常像静态变量,只不过多了线程属性。

      在同一个线程中,一个线程局部存储对象只会初始化一次,即使在某个函数中被多次调用,这一点和单线程中的静态对象非常相似。对象的存储在线程开始时分配,相对应的,对象的销毁也只会发生一次,通常发生在线程退出的时刻,接下看几个例子。

      thread_local 只对声明于命名空间作用域的对象、声明于块作用域的对象以及静态数据成员允许。它指示对象拥有线程存储期。它能与 static 或 extern 结合,以分别指定内部或外部链接(除了静态数据成员始终拥有外部链接),但附加的 static 不影响存储期。

二、示例

2.1.全局变量
#include <iostream>
#include <thread>

thread_local int g_nx = 1;

void thread_func(const std::string& thread_name) {
	for (int i = 0; i < 50; i++) {
		
		printf("thread[%s]:g_nx = %d\n", thread_name.c_str(),g_nx);
		g_nx++;
	}
}

int main() {
	std::thread t1(thread_func, "t1");
	std::thread t2(thread_func, "t2");
	t1.join();
	t2.join();
	system("pause");
	return 0;
}

结果:
在这里插入图片描述
从结果可以看出,每个线程各自拷贝了一份数据。
在这里插入图片描述

2.2.局部变量

修改线程函数如下:

void thread_func(const std::string& thread_name) {
	for (int i = 0; i < 50; i++) 
	{
		thread_local int g_nx = 1;
		printf("thread[%s]:g_nx = %d\n", thread_name.c_str(),g_nx);
		g_nx++;
	}
}

结果和“一、全局变量”相同,g_nx只在线程创建的时候执行了一次。那如果换成static,会有什么反应呢?

void thread_func(const std::string& thread_name) {
	for (int i = 0; i < 50; i++) 
	{
		std::lock_guard<std::mutex> lc(mutexx);
		static  int g_nx = 1;
		printf("thread[%s]:g_nx = %d\n", thread_name.c_str(),g_nx);
		g_nx++;
	}
}

在这里插入图片描述

2.3.类对象
class A {
public:
	A() {
		
		std::cout << "构造函数\n";
	}

	~A() {
	
		std::cout << "析构函数\n";
	}

	
	int get_value() 
	{
		return counter++;
	}
private:
	int counter = 0;
};

void thread_func(const std::string& thread_name) {
	for (int i = 0; i < 3; ++i) 
	{
		thread_local std::shared_ptr<A> spA(new A());
		printf("thread[%s]:a.counter = %d\n", thread_name.c_str(), spA->get_value());
		
	}
	return;
}


int main() 
{
	{
		std::thread t1(thread_func, "t1");
		std::thread t2(thread_func, "t2");
		t1.join();
		t2.join();

	}
	
	system("pause");
	return 0;
}

结果:
在这里插入图片描述

2.4.类成员变量

thread_local 作为类成员变量时必须是 static 的!

class A {
public:
	A() {
		
		std::cout << "构造函数\n";
	}

	~A() {
	
		std::cout << "析构函数\n";
	}

	static int inline m_sN = 15;
	static int inline thread_local  m_tlN = 15;
};

void thread_func(const std::string& thread_name)
{
	A a;
	for (int i = 0; i < 3; ++i) 
	{
		a.m_sN--;
		a.m_tlN--;
		printf("thread[%s]:m_sN = %d,m_tlN =%d \n", thread_name.c_str(),a.m_sN,a.m_tlN);
		
	}
	return;
}


int main() 
{
	{
		std::thread t1(thread_func, "t1");
		std::thread t2(thread_func, "t2");
		t1.join();
		t2.join();

	}
	
	system("pause");
	return 0;
}

结果:
在这里插入图片描述

huang@huang:~/wheeltec$ catkin_make Base path: /home/huang/wheeltec Source space: /home/huang/wheeltec/src Build space: /home/huang/wheeltec/build Devel space: /home/huang/wheeltec/devel Install space: /home/huang/wheeltec/install #### #### Running command: "make cmake_check_build_system" in "/home/huang/wheeltec/build" #### -- Using CATKIN_DEVEL_PREFIX: /home/huang/wheeltec/devel -- Using CMAKE_PREFIX_PATH: /opt/ros/noetic -- This workspace overlays: /opt/ros/noetic -- Found PythonInterp: /usr/bin/python3 (found suitable version "3.8.10", minimum required is "3") -- Using PYTHON_EXECUTABLE: /usr/bin/python3 -- Using Debian Python package layout -- Using empy: /usr/lib/python3/dist-packages/em.py -- Using CATKIN_ENABLE_TESTING: ON -- Call enable_testing() -- Using CATKIN_TEST_RESULTS_DIR: /home/huang/wheeltec/build/test_results -- Forcing gtest/gmock from source, though one was otherwise available. -- Found gtest sources under '/usr/src/googletest': gtests will be built -- Found gmock sources under '/usr/src/googletest': gmock will be built -- Found PythonInterp: /usr/bin/python3 (found version "3.8.10") -- Using Python nosetests: /usr/bin/nosetests3 -- catkin 0.8.12 -- BUILD_SHARED_LIBS is on -- BUILD_SHARED_LIBS is on WARNING: package "orb_slam2_ros" should not depend on metapackage "image_common" but on its packages instead -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- ~~ traversing 72 packages in topological order: -- ~~ - lslidar (metapackage) -- ~~ - navigation (metapackage) -- ~~ - opencv_tests -- ~~ - aruco_msgs -- ~~ - lslidar_msgs -- ~~ - nmea_msgs -- ~~ - ublox (metapackage) -- ~~ - vision_opencv (metapackage) -- ~~ - world_canvas_msgs -- ~~ - ollama_chat_ros -- ~~ - map_server -- ~~ - sh_manager -- ~~ - sparse_bundle_adjustment -- ~~ - open_karto -- ~~ - cv_bridge -- ~~ - aruco -- ~~ - darknet_ros_msgs -- ~~ - image_geometry -- ~~ - bodyreader -- ~~ - darknet_ros -- ~~ - depthimage_to_laserscan -- ~~ - ipa_building_msgs -- ~~ - ipa_building_navigation -- ~~ - kcf_track -- ~~ - ros_tensorflow -- ~~ - rplidar_ros -- ~~ - simple_follower -- ~~ - astra_camera -- ~~ - imu_tf_broadcaster -- ~~ - aruco_ros -- ~~ - fdilink_ahrs -- ~~ - ldlidar -- ~~ - ldlidar_14 -- ~~ - lslidar_driver -- ~~ - rrt_exploration -- ~~ - slam_karto -- ~~ - amcl -- ~~ - fake_localization -- ~~ - ipa_room_exploration -- ~~ - ira_laser_tools -- ~~ - laserscan_merger -- ~~ - orb_slam2_ros -- ~~ - turn_on_wheeltec_robot -- ~~ - hipnuc_imu -- ~~ - ublox_serialization -- ~~ - ublox_msgs -- ~~ - ublox_gps -- ~~ - ublox_msg_filters -- ~~ - qt_ros_test -- ~~ - usb_cam -- ~~ - voxel_grid -- ~~ - costmap_2d -- ~~ - nav_core -- ~~ - base_local_planner -- ~~ - carrot_planner -- ~~ - clear_costmap_recovery -- ~~ - dwa_local_planner -- ~~ - move_slow_and_clear -- ~~ - navfn -- ~~ - global_planner -- ~~ - rotate_recovery -- ~~ - move_base -- ~~ - teb_local_planner -- ~~ - web_video_server -- ~~ - wheeltec_aiui_ros -- ~~ - wheeltec_gps_driver -- ~~ - wheeltec_joy -- ~~ - wheeltec_multi -- ~~ - wheeltec_robot_rc -- ~~ - wheeltec_yolo_action -- ~~ - xf_mic_asr_offline_circle -- ~~ - yesense_imu -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- +++ processing catkin metapackage: 'lslidar' -- ==> add_subdirectory(lsx10/lslidar) -- +++ processing catkin metapackage: 'navigation' -- ==> add_subdirectory(navigation-noetic-devel/navigation) -- +++ processing catkin package: 'opencv_tests' -- ==> add_subdirectory(vision_opencv-noetic/opencv_tests) -- +++ processing catkin package: 'aruco_msgs' -- ==> add_subdirectory(aruco_ros-noetic-devel/aruco_msgs) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- aruco_msgs: 2 messages, 0 services -- +++ processing catkin package: 'lslidar_msgs' -- ==> add_subdirectory(lsx10/lslidar_msgs) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- lslidar_msgs: 5 messages, 0 services -- +++ processing catkin package: 'nmea_msgs' -- ==> add_subdirectory(wheeltec_gps/nmea_msgs-master) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- nmea_msgs: 7 messages, 0 services -- +++ processing catkin metapackage: 'ublox' -- ==> add_subdirectory(wheeltec_gps/ublox-master/ublox) -- +++ processing catkin metapackage: 'vision_opencv' -- ==> add_subdirectory(vision_opencv-noetic/vision_opencv) -- +++ processing catkin package: 'world_canvas_msgs' -- ==> add_subdirectory(world_canvas_msgs) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- world_canvas_msgs: 5 messages, 17 services -- +++ processing catkin package: 'ollama_chat_ros' -- ==> add_subdirectory(ollama_chat_ros) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- ollama_chat_ros: 0 messages, 1 services -- Installing devel-space wrapper /home/huang/wheeltec/src/ollama_chat_ros/scripts/ollama_topic_client.py to /home/huang/wheeltec/devel/lib/ollama_chat_ros -- Installing devel-space wrapper /home/huang/wheeltec/src/ollama_chat_ros/scripts/ollama_topic_server.py to /home/huang/wheeltec/devel/lib/ollama_chat_ros -- Installing devel-space wrapper /home/huang/wheeltec/src/ollama_chat_ros/scripts/chat_client.py to /home/huang/wheeltec/devel/lib/ollama_chat_ros -- Installing devel-space wrapper /home/huang/wheeltec/src/ollama_chat_ros/scripts/chat_service.py to /home/huang/wheeltec/devel/lib/ollama_chat_ros -- +++ processing catkin package: 'map_server' -- ==> add_subdirectory(navigation-noetic-devel/map_server) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found version "1.71.0") found components: filesystem -- +++ processing catkin package: 'sh_manager' -- ==> add_subdirectory(sh_manager) -- +++ processing catkin package: 'sparse_bundle_adjustment' -- ==> add_subdirectory(slam_karto/sparse_bundle_adjustment-melodic-devel) -- +++ processing catkin package: 'open_karto' -- ==> add_subdirectory(slam_karto/open_karto-melodic-devel) -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found version "1.71.0") found components: thread -- +++ processing catkin package: 'cv_bridge' -- ==> add_subdirectory(vision_opencv-noetic/cv_bridge) -- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython3.8.so (found version "3.8.10") -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found version "1.71.0") found components: python -- Found OpenCV: /usr (found suitable version "4.2.0", minimum required is "4.2") found components: opencv_core opencv_imgproc opencv_imgcodecs -- Found PythonLibs: /usr/lib/x86_64-linux-gnu/libpython3.8.so (found suitable version "3.8.10", minimum required is "3.8") -- +++ processing catkin package: 'aruco' -- ==> add_subdirectory(aruco_ros-noetic-devel/aruco) -- Found OpenCV: /usr (found suitable version "4.2.0", minimum required is "4.2.0") -- +++ processing catkin package: 'darknet_ros_msgs' -- ==> add_subdirectory(darknet_ros/darknet_ros_msgs) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Generating .msg files for action darknet_ros_msgs/CheckForObjects /home/huang/wheeltec/src/darknet_ros/darknet_ros_msgs/action/CheckForObjects.action -- darknet_ros_msgs: 10 messages, 0 services -- +++ processing catkin package: 'image_geometry' -- ==> add_subdirectory(vision_opencv-noetic/image_geometry) -- Found OpenCV: /usr (found version "4.2.0") -- +++ processing catkin package: 'bodyreader' -- ==> add_subdirectory(bodyreader) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- bodyreader: 9 messages, 0 services -- +++ processing catkin package: 'darknet_ros' -- ==> add_subdirectory(darknet_ros/darknet_ros) -- Darknet path dir = /home/huang/wheeltec/src/darknet_ros/darknet -- Searching for X11... -- X11_INCLUDE_DIR: /usr/include -- X11_LIBRARIES: /usr/lib/x86_64-linux-gnu/libSM.so/usr/lib/x86_64-linux-gnu/libICE.so/usr/lib/x86_64-linux-gnu/libX11.so/usr/lib/x86_64-linux-gnu/libXext.so -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found version "1.71.0") found components: thread -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Checking and downloading yolov2-tiny.weights if needed ... -- Checking and downloading yolov3.weights if needed ... -- Checking and downloading yolov2.weights if needed ... -- +++ processing catkin package: 'depthimage_to_laserscan' -- ==> add_subdirectory(depthimage_to_laserscan-melodic-devel) -- +++ processing catkin package: 'ipa_building_msgs' -- ==> add_subdirectory(ipa_exploration/ipa_building_msgs) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Generating .msg files for action ipa_building_msgs/MapSegmentation /home/huang/wheeltec/src/ipa_exploration/ipa_building_msgs/action/MapSegmentation.action -- Generating .msg files for action ipa_building_msgs/FindRoomSequenceWithCheckpoints /home/huang/wheeltec/src/ipa_exploration/ipa_building_msgs/action/FindRoomSequenceWithCheckpoints.action -- Generating .msg files for action ipa_building_msgs/RoomExploration /home/huang/wheeltec/src/ipa_exploration/ipa_building_msgs/action/RoomExploration.action -- ipa_building_msgs: 23 messages, 2 services -- +++ processing catkin package: 'ipa_building_navigation' -- ==> add_subdirectory(ipa_exploration/ipa_building_navigation) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Found OpenCV: /usr (found suitable version "4.2.0", minimum required is "4") -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found version "1.71.0") found components: system thread chrono -- +++ processing catkin package: 'kcf_track' -- ==> add_subdirectory(kcf_track) -- Found OpenCV: /usr (found version "4.2.0") -- OpenCV_LIB_DIR: -- OpenCV_INCLUDE_DIRS: /usr/include/opencv4 -- +++ processing catkin package: 'ros_tensorflow' -- ==> add_subdirectory(ros_tensorflow) -- +++ processing catkin package: 'rplidar_ros' -- ==> add_subdirectory(rplidar_ros) -- +++ processing catkin package: 'simple_follower' -- ==> add_subdirectory(simple_follower) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- simple_follower: 1 messages, 0 services -- +++ processing catkin package: 'astra_camera' -- ==> add_subdirectory(ros_astra_camera-main) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found version "1.71.0") -- ORRBEC Machine : x86_64 -- ORRBEC Machine Bits : 64 -- ORRBEC : x64 -- libuvc .. -- astra_camera: 3 messages, 9 services -- +++ processing catkin package: 'imu_tf_broadcaster' -- ==> add_subdirectory(imu_tf_broadcaster) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Installing devel-space wrapper /home/huang/wheeltec/src/imu_tf_broadcaster/scripts/imu_tf_broadcaster.py to /home/huang/wheeltec/devel/lib/imu_tf_broadcaster -- +++ processing catkin package: 'aruco_ros' -- ==> add_subdirectory(aruco_ros-noetic-devel/aruco_ros) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- +++ processing catkin package: 'fdilink_ahrs' -- ==> add_subdirectory(fdilink_ahrs) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- +++ processing catkin package: 'ldlidar' -- ==> add_subdirectory(ldlidar_stl06n_ros1/ldlidar) -- optional:-std=c++11 -Wall -Wextra -- +++ processing catkin package: 'ldlidar_14' -- ==> add_subdirectory(ldlidar_14) -- #define USE_SLBF -- +++ processing catkin package: 'lslidar_driver' -- ==> add_subdirectory(lsx10/lslidar_driver) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy CMake Warning at /opt/ros/noetic/share/catkin/cmake/catkin_package.cmake:166 (message): catkin_package() DEPENDS on 'boost' but neither 'boost_INCLUDE_DIRS' nor 'boost_LIBRARIES' is defined. Call Stack (most recent call first): /opt/ros/noetic/share/catkin/cmake/catkin_package.cmake:102 (_catkin_package) lsx10/lslidar_driver/CMakeLists.txt:22 (catkin_package) -- +++ processing catkin package: 'rrt_exploration' -- ==> add_subdirectory(rrt_exploration) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- rrt_exploration: 1 messages, 0 services -- +++ processing catkin package: 'slam_karto' -- ==> add_subdirectory(slam_karto/slam_karto-melodic-devel) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- +++ processing catkin package: 'amcl' -- ==> add_subdirectory(navigation-noetic-devel/amcl) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- +++ processing catkin package: 'fake_localization' -- ==> add_subdirectory(navigation-noetic-devel/fake_localization) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- +++ processing catkin package: 'ipa_room_exploration' -- ==> add_subdirectory(ipa_exploration/ipa_room_exploration) -- Using these message generators: gencpp;geneus;genlisp;gennodejs;genpy -- Found OpenCV: /usr (found suitable version "4.2.0", minimum required is "4") -- Found Boost: /usr/lib/x86_64-linux-gnu/cmake/Boost-1.71.0/BoostConfig.cmake (found version "1.71.0") found components: system chrono thread -- Gurobi has not been found -- Could NOT find GUROBI (missing: GUROBI_LIBRARY GUROBI_CXX_LIBRARY GUROBI_INCLUDE_DIR) -- Gurobi include dirs: -- Gurobi lib dirs: -- Checking for module 'coinutils' -- Found coinutils, version 2.11.4 -- Checking for module 'osi-clp' -- No package 'osi-clp' found CMake Error at /usr/share/cmake-3.16/Modules/FindPkgConfig.cmake:463 (message): A required package was not found Call Stack (most recent call first): /usr/share/cmake-3.16/Modules/FindPkgConfig.cmake:643 (_pkg_check_modules_internal) ipa_exploration/ipa_room_exploration/CMakeLists.txt:78 (pkg_check_modules) -- Configuring incomplete, errors occurred! See also "/home/huang/wheeltec/build/CMakeFiles/CMakeOutput.log". See also "/home/huang/wheeltec/build/CMakeFiles/CMakeError.log". make: *** [Makefile:1062:cmake_check_build_system] 错误 1 Invoking "make cmake_check_build_system" failed
最新发布
08-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

发如雪-ty

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值