thread_utils.h
Go to the documentation of this file.
1 
10 /*
11  * libmavconn
12  * Copyright 2014,2015,2016 Vladimir Ermakov, All rights reserved.
13  *
14  * This file is part of the mavros package and subject to the license terms
15  * in the top-level LICENSE file of the mavros repository.
16  * https://github.com/mavlink/mavros/tree/master/LICENSE.md
17  */
18 
19 #pragma once
20 
21 #include <thread>
22 #include <string>
23 #include <cstdio>
24 #include <sstream>
25 #include <pthread.h>
26 
27 namespace mavconn {
28 namespace utils {
29 
34 template<typename ... Args>
35 std::string format(const std::string &fmt, Args ... args)
36 {
37  // C++11 specify that string store elements continously
38  std::string ret;
39 
40  auto sz = std::snprintf(nullptr, 0, fmt.c_str(), args...);
41  ret.reserve(sz + 1); ret.resize(sz); // to be sure there have room for \0
42  std::snprintf(&ret.front(), ret.capacity() + 1, fmt.c_str(), args...);
43  return ret;
44 }
45 
54 template<typename ... Args>
55 bool set_this_thread_name(const std::string &name, Args&& ... args)
56 {
57  auto new_name = format(name, std::forward<Args>(args)...);
58 
59 #ifdef __APPLE__
60  return pthread_setname_np(new_name.c_str()) == 0;
61 #else
62  pthread_t pth = pthread_self();
63  return pthread_setname_np(pth, new_name.c_str()) == 0;
64 #endif
65 }
66 
70 template <typename T>
71 inline const std::string to_string_ss(T &obj)
72 {
73  std::ostringstream ss;
74  ss << obj;
75  return ss.str();
76 }
77 
78 constexpr size_t operator"" _KiB (unsigned long long sz)
79 {
80  return sz * 1024;
81 }
82 } // namespace utils
83 } // namespace mavconn
std::string format(const std::string &fmt, Args...args)
Make printf-formatted std::string.
Definition: thread_utils.h:35
const std::string to_string_ss(T &obj)
Convert to string objects with operator <<.
Definition: thread_utils.h:71
bool set_this_thread_name(const std::string &name, Args &&...args)
Set name to current thread, printf-like.
Definition: thread_utils.h:55


libmavconn
Author(s): Vladimir Ermakov
autogenerated on Tue Jun 1 2021 02:36:21