我应该使用什么方法在Windows多线程中分配内存 [英] What method should i use to allocate memory in windows Multithread

查看:91
本文介绍了我应该使用什么方法在Windows多线程中分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为标题,我在一个Windows线程(由CreateThread API创建)中使用malloc并在调用CreateThread函数的调用函数中释放它,它首先工作正常。但是当我开始一个新线程时,它会抛出一个访问异常。在调试模式下,调试发布版本没有问题,但运行发布版本会引发异常。

As the title,i use malloc in a windows thread(created by CreateThread API) and free it in calling function which call the CreateThread function and it works fine first. But when i started a new thread , it throws a access exception. And in Debug mode it has no problem the same as debug the release version but running the release version it throws the exception.

推荐答案





你所描述的只是一个糟糕的设计。你不应该使用ThreadFunction malloc并释放你所描述的调用函数中的内存。这可能会导致问题,尤其是在多线程应用程序中。相反,你应该使用以下模式:



模式I.

- 使用malloc在调用线程中分配内存。

- 然后将指针传递给新创建的线程的分配内存(我想新线程会在其中填充一些数据,或者等等)

- 线程完成后,在调用中线程使用已经存储在内存中的数据。

- 最后,通过在调用线程中使用同步方法检查新线程的退出。如果已经退出,则释放内存。



模式II。

- 将内存处理留给新创建的线程。新创建的线程将分配所需的内存并在退出之前释放它。



如果内存应在所有线程之间共享,那么你需要在创建之前分配内存线程并在所有线程完成后释放它(您必须使用线程同步机制)。请注意,您需要使用某些线程同步机制来同步线程!



每次必须确保:

- 每个 malloc 你打电话免费

- 每次你打电话删除
- 对于每个新[] ,您拨打删除[]



希望这会有所帮助。



祝你好运,



JK



[更新:重新整理了整个答案。删除了错误代码并添加了新内容。]
Hi,

what you described is simply a bad design. You shall no malloc the ThreadFunction and free the memeory in the calling function as you described. This can cause problems especially in multithreaded applications. Instead you shall use the following pattern:

Pattern I.
- use malloc to allocate memory in the calling thread.
- then pass the pointer to the allocated memory to the newly created thread (I suppose the new thread fill some data in it, or so)
- after the thread finishes, in the calling thread use the data that hase been stored in the memory.
- finally, by using synchronization method in the calling thread check for the exit of new thread. Deallocate the memory if it has exited.

Pattern II.
- Leave memory handling to newly created thread. The newly created thread will allocate the required memory and release it before exiting.

If the memory shall be shared among all threads, then you need to allocate the memory before creating the threads and release it after all the threads have finished (you have to use the thread synchronization mechanism). Be aware that you need to synchronize the threads with some thread synchronization mechanism !

Every time you must make sure that:
- for every malloc you call free
- for every new you call delete
- for every new[] you call delete [].

Hope this helps.

Best regards,

J. K.

[Updates: Restructured the entire answer. Removed buggy code and added new stuff as well.]


这篇关于我应该使用什么方法在Windows多线程中分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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