0

I would like to store a class of my own in a map, with the key being of type pthread_t.(Each object of my class contains a pthread_t data member so I want each instance to be associated with that pthread_t as a key, in a map) The problem is pthread_t can't be compared, only with pthread_equal so I can't put it in a map as a key.

I have seen unordered_map, but how can I implement a hash function for pthread_t?

Until now I thought about comparing them using pthread_self(), but that's also impossible since the returned value is pthread_t, and I don't want to use the fact that this is just a typedef for unsigned long int.

If using some sort of map is not possible, how can I store pthread_t's objects in a container and find them fast using pthread_self() funcion?

dor132
  • 183
  • 1
  • 1
  • 8
  • Why not use a vector? – Kerrek SB Apr 10 '16 at 13:06
  • May be this helps a bit: http://stackoverflow.com/questions/558469/how-do-i-get-a-thread-id-from-an-arbitrary-pthread-t – πάντα ῥεῖ Apr 10 '16 at 13:07
  • @KerrekSB, I am using a vector now but that means I have to search for a thread in O(n), my question is if it's possible to search better using map or something like that... – dor132 Apr 10 '16 at 13:11
  • @πάνταῥεῖ, I don't really understand the answers in this post. Some of them use the assumption that pthread_t is an unsigned long int, something I would like to avoid. Correct me if I'm wrong, but what I understand from the first answer is that I can give each thread an ID I can choose manually? – dor132 Apr 10 '16 at 13:13
  • @dor132 _"is that I can give each thread an ID I can choose manually?"_ Not in a portable way unfortunately. The other answers are more useful for what you want to achieve. – πάντα ῥεῖ Apr 10 '16 at 13:15
  • @πάνταῥεῖ so I can gettid instead or with pthread_self() to achieve this? – dor132 Apr 10 '16 at 13:19

1 Answers1

1

This way it should work :

bool myCmp(const pthread_t &a, const pthread_t &b)
{
  return memcmp(&a, &b, sizeof(pthread_t)) < 0;
}

map<pthread_t, myDataType, myCmp> myMap;
SamY
  • 11
  • 1