如果我在C ++中的一个线程中分配内存,我可以在另一个线程中释放它 [英] If I allocate memory in one thread in C++ can I de-allocate it in another

查看:922
本文介绍了如果我在C ++中的一个线程中分配内存,我可以在另一个线程中释放它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在C ++中的一个线程中分配内存(new或malloc),我可以在另一个线程中分配内存,或者必须同时出现在同一个线程中?理想情况下,我想避免这一点,但我很想知道是合法,非法还是实现依赖。

If I allocate memory in one thread in C++ (either new or malloc) can I de-allocate it in another, or must both occur in the same thread? Ideally, I'd like to avoid this in the first place, but I'm curious to know is it legal, illegal or implementation dependent.

编辑: 我目前使用的编译器包括VS2003,VS2008和Embedded C ++ 4.0,针对XP,Vista,Windows 7和各种口味的Windows CE / PocketPC&移动。因此,基本上所有的微软,但跨越一系列深奥的平台。

The compilers I'm currently using include VS2003, VS2008 and Embedded C++ 4.0, targetting XP, Vista, Windows 7 and various flavours of Windows CE / PocketPC & Mobile. So basically all Microsoft but across an array of esoteric platforms.

推荐答案

通常,malloc / new / free / delete多线程系统是线程安全的,所以这应该没有问题 - 并且在一个线程中分配,在另一个线程中释放是一个很常见的事情。

Generally, malloc/new/free/delete on multi threaded systems are thread safe, so this should be no problem - and allocating in one thread , deallocating in another is a quite common thing to do.

由于线程是一个实现特性,它肯定是实现依赖的 - 例如某些系统需要您链接到多线程运行时库。

As threads are an implementation feature, it certainly is implementation dependant though - e.g. some systems require you to link with a multi threaded runtime library.

这篇关于如果我在C ++中的一个线程中分配内存,我可以在另一个线程中释放它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆