user777305
user777305

Reputation: 209

Boost::this_thread::get_id() without string operation

i'm in a situation where i need to get boost::thread::id into a variable, but this variable is NOT a string, neither a string operation is allowed. is that possible?

maybe something like

char *tid = (casting something) boost::this_thread::get_id()

this is c++ on unix system. the reason why avoiding using string operation is because it slows down the whole application speed. thanks before.

Upvotes: 2

Views: 8172

Answers (2)

David Schwartz
David Schwartz

Reputation: 182779

In any event, your question seems to be entirely based on a misconception. If you want to get the boost::thread::id into a variable, the variable should be of type boost::thread::id. Like this:

boost::thread::id MyVariable = boost::thread::get_id();

No strings are involved at all. Why are you trying to cast it to a char *?

If your threads need to get their IDs so often that it's creating a bottleneck, you are likely doing something horribly wrong. Why do you need a thread's ID so much?

Update: Okay, so you need a thread ID that has specific semantics. You need to assign threads IDs that have the semantics you require. (There is no guarantee that whatever ID the threads already have is usable in a file name.) In pseudo-code:

  1. Call get_id.
  2. Look up the ID you retrieved in a map.
  3. If you found an entry for this ID, return its value, you're done.
  4. This thread has no ID that can be used in a file name. So assign it one. Store the pair of the ID you got from get_id and the ID you just assigned in the map. This will ensure the next time you try to get an entry for this thread, you will get the same one.

Alternatively, your platform may have a function that provides the semantics you need. For example, Linux has gettid and NT has GetCurrentThreadId.

Upvotes: 6

rve
rve

Reputation: 6055

What about:

std::ostringstream oss;
oss << boost::thread::get_id();
std::string idAsString = oss.str();

See the documentation on boost::thread::id

Update: Since you already use boost, why not use:

std::string id = boost::lexical_cast<std::string>(boost::thread::get_id());

Also, as you are doing this only at the beginning speed should not be an issue.

Upvotes: 4

Related Questions