From: | "Tim Keitt" <tkeitt(at)keittlab(dot)org> |
---|---|
To: | pgsql-hackers(at)postgresql(dot)org |
Subject: | pointer scope and memory contexts |
Date: | 2008-11-06 01:31:57 |
Message-ID: | 6262c54c0811051731s90245a1nea1321652d77c3d@mail.gmail.com |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-hackers |
I am working on a set returning function and have a question about
switching memory contexts. Basically, what I want to know is whether
memory allocated in one context can be referenced when a different
context is current. The docs give examples like:
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate some memory that needs to span calls */
my_ptr = (a_type *) palloc(size);
MemoryContextSwitchTo(oldcontext);
}
funcctx = SRF_PERCALL_SETUP();
/* can I now dereference here? Is it necessary to manually switch
to multi_call_memory_ctx? */
some_function(my_ptr[0]);
...
In a related question, do I only need to switch to
multi_call_memory_ctx when allocating memory that needs to be
referenced in subsequent calls? Would the following make sense?
if (SRF_IS_FIRSTCALL())
{
funcctx = SRF_FIRSTCALL_INIT();
/* this will be deallocated at the end of the first call, right? */
scratch_ptr = (a_type *) palloc(size);
oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx);
/* allocate some memory that needs to span calls */
my_ptr = (a_type *) palloc(size);
MemoryContextSwitchTo(oldcontext);
/* can I dereference my_ptr here? */
func_called_once(scratch_ptr, my_ptr);
...
}
/* per call stuff follows... */
In other words, if I have allocations that only are needed during the
first call, can I allocate them outside of the multi_call_memory_ctx
(so that they do not live past the first call) and only allocate the
memory needed for multiple calls within the multi_call_memory_ctx?
One last question: if I call SPI_finish, on the first call, do I need
to switch contexts in the per-call section? (I saw some example code
that suggested one needs to switch contexts back to
multi_call_memory_ctx after SPI_finish.)
Thanks.
THK
--
Timothy H. Keitt
http://www.keittlab.org/
From | Date | Subject | |
---|---|---|---|
Next Message | Gregory Stark | 2008-11-06 01:38:26 | Re: [WIP] In-place upgrade |
Previous Message | Bernd Helmle | 2008-11-06 01:09:07 | Re: Patch for ALTER DATABASE WITH TABLESPACE |