运行时擦除保存 pthread 的变量
我的程序中有一个映射来保存由 pthread_create 方法创建的 pthread(需要一个位置来放置此 pthread),并与相关线程 ID 关联。
pthread函数的最后一个命令中从map中删除pthread是否存在问题?
I have a map in my program to hold the pthreads created by the pthread_create 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如你所说,你持有线程ID。这只是一个数字。而已。
删除元素(数字)不会对您的程序造成任何损害。
编辑:但是您应该检查
std::map
中的擦除元素是否已同步完成。不要忘记 STL 容器可能不是线程安全的。请参阅此问题了解更多信息。编辑2:为了确保您没有同步问题,请执行以下操作:
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 :
我同意 Ashot Martirosyan 提供的答案。我只想补充一点。
如果线程被创建为可连接的,那么您的应用程序将需要调用
pthread_join()
;否则你会泄漏内存。如果映射是记录线程 ID 的唯一位置,那么如果每个线程在其死亡之前从映射中删除了其线程 ID,则您将无法加入线程。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.您可以随时删除数据。但是,如果线程访问此映射,程序中可能会出现竞争条件。如果线程 A 正在退出,但在擦除其数据之前被换出,则线程 B 可能会看到线程 A 的数据并认为线程 A 仍然是可行的线程。
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.
您应该使用
pthread_join
或pthread_detach
或创建一个分离的线程,否则有时您会从pthread_create
收到错误消息。对于所有可连接线程,操作系统保留一定量的内存来存储线程返回值。为此目的保留的内存总量是有限的,可能会少于您的预期,因此请分离您不打算加入的所有线程。You should either
pthread_join
orpthread_detach
or create a deteached thread, otherwise you'll get an error frompthread_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.