I have a map in my program to hold the pthreads created by the pthread_creat开发者_运维百科e method (that requires a place to put this pthread), associated with a relevant thread ID.
Is there a problem of erasing the pthread from the map in the last command of the pthread's function?As you said, you are holding thread ID. It's just a number. Nothing more.
Erasing element (number) can't do any harm to your program.
Edit: However you should check, that erasing element in std::map
is done synchronized. Don't forget STL containers can be not thread safe. See this question for more info.
Edit2: To ensure, that you haven't problems with synchronization do following :
pthread_mutex_t mut; //global variable
pthread_mutex_init(&mut,0); //initialize mutex before calling pthread_create()
//and use mutex to prevent synchronization problems in the end of .
pthread_mutex_lock(&mut);
my_map.erase(key);
pthread_mutex_unlock(&mut);
I agree with the answer provided by Ashot Martirosyan. I just want to add one other point.
If the threads are created as joinable, then your application will need to call pthread_join()
; otherwise you will leak memory. If the map is the only place where you record the thread IDs, then you won't be able to join with the threads if each thread has removed its thread ID from the map just before it died.
You can erase the data whenever you want. However there could be race conditions in your program if threads access this map. if thread A is exiting but gets swapped out before it erases its data, thread B might see thread A's data and think that thread A is still a viable thread.
You should either pthread_join
or pthread_detach
or create a deteached thread, otherwise you'll get an error from pthread_create
sometime. For all joinable threads OS reserves some amount of memory to store the thread return value. Total amount of memory reserved for such purpose is limited and can be less that you expect, so detatch all threads you are not going to join.
精彩评论