You can take a look at the following paper(If you havent already because what you described in second message is what this paper does). Fast-efficient fixed size memory pool[^]
meerokh
Posts
-
How to solve memory resource management problems in C++ -
Access a pointer value changed in another classyeah i am creating a multi threaded application but i am not allowed to use any libraries etc. Its a bare metal implementation so i need to find a way to do it myself. I am using Pthreads just to emulate the physical cores of a system.
-
Access a pointer value changed in another classFor synchronization purpose, I am implementing a wait function that is gonna wait until a package is executed. I have following code in user application
bool finished;
function(){
int id = createpackage(&finished);// user creates a package(basically another function) for the execution
wait(&finished)//if i need to wait for the result of above created package
// do remaining stuff
}Inside the library(i am developing), i am trying to do this package.cpp
createpackage(bool* finished){
*finished = false;
package pack(function, arguments, finished);// this calls the constructor of package//package contructor
package::package(){
//other memeber variables inside ctor
m_packagefinished = *finished; // As package is being created so finished = falsevoid package::setHandle(){
lock
//i am not sure how to set the value of finished to true so that it reflect the change when i access it in wait(). Any ideas??
unlock
}}
In another class i am executing the package and want to set the m_finished to true after packge is being executed.
packageinstance.execute();
packageinstance.setHandle();//Wait
function(implemented in a different class) is as follows:wait(bool * finished){
while(*finished == false)
yeild(); //If the package is not being executed yet, yeild to another package and execute it
}The problem is that how can i get the correct value of finished inside the wait function.
-
Access a class instance based on its IDIt got stored in an instance of class
WorkPackage
which in turn is added topackagequeue
WorkPackage.hclass WorkPackage {
private:
WorkPackageState wp_state;
void (*m_action)(void*);
void* m_arguments = nullptr;
protected:
static int id;public:
WorkPackage(){};
WorkPackage(void (*action)(void*), void* arguments);
void destroystack();
void execute();
static void setState(WorkPackageState wp_state);
WorkPackageState getState();
Stack Wp_localstack;
fcontext_t m_context;
int packageId;
};Workpackage.cpp
WorkPackage::WorkPackage(void (*action)(void*), void* arguments) {
Wp_localstack.local_stack= Stack::make_stack();
m_action = action;
m_arguments = arguments;
Wp_localstack.local_stack = static_cast (Wp_localstack.local_stack) + 1000;
m_context = make_fcontext(Wp_localstack.local_stack, 1000, m_action);
wp_state = running;
packageId=++id;
}WorkPackageState WorkPackage::getState() {
return state;
}void WorkPackage::execute(int thread_id) {
m_action(m_arguments);
destroystack();
}void WorkPackage::setState(WorkPackageState state) {
WorkPackageState new_state = state;
} -
Access a class instance based on its IDI have two queues in my program,
queue
andwaitingQueue
.queue
contains the workpackage instances that are created by user . After creating a workpackge by a user, if he decides to yield it, i want to change the status of created workpackage towaiting
and add it to thewaitingQueue
. Creation of workpackage returns a unique id of the package that is added to the queue. This is what i want to acheive://Done in user application
int packageId = creatpackage(Function, arguments); // this create a package and adds it to a normal queue
wait(packageId); //wait call yeild function that is part of my library//Inside library
void classname::yeild(int packageId){
set the state of workpackage to Waiting
add the package to WaitingQueue
if(there is another package in WaitingQueue)
Make a switch context to it
else
Go to normal queue and execute the package
}My question is how can i access the workpackage state after which yeild function was called. I thought of accessing it based on id somehow(is it even possible??) Based on my full scenario, is there any better approach then what i am doing??
-
How to deallocate memory allocated to a class instanceDestructor is as follows.
WorkPackage::~WorkPackage(){
if (Wp_localstack.local_stack != nullptr)
{
Stack::release(Wp_localstack.local_stack);
}
}and
release()
is follows.void Stack::release(void * stack ){
int core_id= coreNumber::getInstance()->getCoreID(); //Get the thread id which called the dtor and release
WPManagerProviderSingleton& singletonObj =
WPManagerProviderSingleton::getInstance();
WorkPackageManager &wpm = singletonObj.getWpmInstance(core_id);//Based on thread id, select the workpackage manager(every thread has its own manager) to deallocate the stack from its respective Memory pool
wpm.PerThreadMemPool.DeAllocate(stack);
} -
How to deallocate memory allocated to a class instancerear
andfront
are the indices of a circular array andsize
is queue length.data
is the instance of theWorkPackage
that is being retrieved and returned back for execution. WorkPackage ctorWorkPackage::WorkPackage(void (*action)(void*), void* arguments) {
Wp_localstack.local_stack= Stack::make_stack();
m_action = action;
m_arguments = arguments;
m_context = make_fcontext(Wp_localstack.local_stack, 1000, m_action);//function to save the context of current work package for context switching purpose.WorkPackage dtor
WorkPackage::~WorkPackage(){
Stack::release(Wp_localstack.local_stack); //When a workpackage finishes stack allocated to it must be deallocated
} -
How to deallocate memory allocated to a class instanceIn constructor of my class
WorkPackage
, I am allocating a stack to each instance of workpackage and adding it to a queue. When a workpackage gets executed, the allocated stack get released in class destructor. The problem is that my destructor gets called before the execution of workpackage and program crashes with segmentation fault. I looked it up and thought that it is because of when i get the package from the queue: PackageQueue.cppWorkPackage PackageQueue::GetWorkPackage(){
if (isEmpty())
{
return WorkPackage(); // return an empty work package
}
pthread_mutex_lock(&getlock);
WorkPackage data=WorkPackageQueue[front];
if (front == rear)
{
rear = -1;
front = -1;
}else if (front == 0) front = size-1; else front--; pthread\_mutex\_unlock(&getlock); return WorkPackage(data); }
I created a copy contructor to allocate a new stack to the instance in case of deletion after
GetWorkPackage
functionWorkPackage::WorkPackage(const WorkPackage& rhs){
Wp_localstack.local_stack= Stack::make_stack();
m_action=rhs.m_action;
m_arguments=rhs.m_arguments;
}But the problem is still there..Need hints to how can i do this correctly. I will provide more code if needed
-
Cant call an assembly function in c++ codeThanks alot it worked
-
Cant call an assembly function in c++ codeMy project structure in eclipse is as follows
Coroutines
Src
DebugCode for make_fcontext is in src folder in file "make_x86_64_sysv_elf_gas.S"
.text
.globl make_fcontext
.type make_fcontext,@function
.align 16
make_fcontext:
/* first arg of make_fcontext() == top of context-stack */
movq %rdi, %rax/\* shift address in RAX to lower 16 byte boundary \*/ andq $-16, %rax /\* reserve space for context-data on context-stack \*/ /\* on context-function entry: (RSP -0x8) % 16 == 0 \*/ leaq -0x40(%rax), %rax /\* third arg of make\_fcontext() == address of context-function \*/ /\* stored in RBX \*/ movq %rdx, 0x28(%rax) /\* save MMX control- and status-word \*/ stmxcsr (%rax) /\* save x87 control-word \*/ fnstcw 0x4(%rax) /\* compute abs address of label trampoline \*/ leaq trampoline(%rip), %rcx /\* save address of trampoline as return-address for context-function \*/ /\* will be entered after calling jump\_fcontext() first time \*/ movq %rcx, 0x38(%rax) /\* compute abs address of label finish \*/ leaq finish(%rip), %rcx /\* save address of finish as return-address for context-function \*/ /\* will be entered after context-function returns \*/ movq %rcx, 0x30(%rax) ret /\* return pointer to context-data \*/
trampoline:
/* store return address on stack */
/* fix stack alignment */
push %rbp
/* jump to context-function */
jmp *%rbxfinish:
/* exit code is zero */
xorq %rdi, %rdi
/* exit application */
call _exit@PLT
hlt
.size make_fcontext,.-make_fcontext/* Mark that we don't need executable stack. */
.section .note.GNU-stack,"",%progbits -
Cant call an assembly function in c++ codeI am trying to implement coroutines in c++ (I had to reinvent the wheel for my project). coroutine.h
class coroutine {
public:
void (*action1)(int);
Stack local_stack;
coroutine(void (*action)(int ), int id); ///< will create coroutine
~coroutine();
static void yield();
};coroutine.cpp
coroutine *global_coro;
fcontext_t context_array[2];
coroutine :: coroutine(void (*action)(int), int id)
{
global_coro=this;
action1=action;
fcontext_t f_ctx = make_fcontext(global_coro->local_stack.local_stack, 1000, global_coro->action1);//Save the current context of coroutine for the sake of making switch context.
// make_fcontext is in .S file taken from boost::context
context_array[0]=f_ctx; // Global Array to store the coroutine context so that i can switch the context
}coroutine::~coroutine(){}
void coroutine::yield(){
transfer_t tr = jump_fcontext(context_of_current_corotine, context_of_next_coroutine ); //Also in .S file
Following is my stack class which allocates a block of memory to every coroutine from a global Memory pool stack.h
extern MemoryPool memPoolObj;
class Stack {
public:
void *local_stack;
MemoryPool& m_memPool=memPoolObj;
Stack();
~Stack();
};Stack.cpp
#include "Stack.h"
MemoryPool memPoolObj;
Stack::Stack() {
auto *local_stack= m_memPool.Allocate();
}
Stack::~Stack() {}Context.h
typedef void* fcontext_t;
struct transfer_t
{
fcontext_t fctx;
void * data;
};extern "C"
transfer_t jump_fcontext( fcontext_t const to, void * vp);
extern "C"
fcontext_t make_fcontext( void * sp, std::size_t size, void (* fn)( int) );Main.cpp
#include "coroutine.h"
void workPackage(int id){
printf("Coroutine with id %d is called\n", id);
coroutine::yield();
printf("Coroutine with id %d is resumed after first yield\n", id);
coroutine::yield();
printf("Coroutine with id %d is resumed after second yield\n", id);
}int main() {
coroutine Coro1(workPackage, 1);
coroutine Coro2(workPackage, 2);
printf("Main is finished \n");
}My program compiles but gives segmentation fault during execution. Valgrind gives the following information and i am not able to solve the problem. I will provide the assembly file also if needed. Any help would be appreciated
Use of uninitialised value of size 8
==24145== at 0x10922B: make_fcontext (in /home/user1/eclipse-workspace/coroutines/Debug/coroutines)
==24145== by 0x10912D -
Invalid operandsHow can i calculate the sum and add it back to struct variable??
-
Invalid operandsI am trying to calculate sum of fibonacci series. Struct arg is defined in header file as follows
struct args {
int number;
int result;
};args user_arguments = { 10, 0 };
void fibonacci (void* arguments)
{
args* local_args = (args*) arguments;
printf("local_args->number = %d\n", local_args->number);
if (local_args->number <= 1) {
local_args->result= 1;
return;
}
int a = (local_args->number)-1;
int b = (local_args->number)-2;
local_args->result =fibonacci(&a) + fibonacci(&b)
return local_args->result;Above function is called from the function below. createPackage is a function provided by another library which gonna execute fabonacci function.
void WorkPackage(void*) {
createPackage(fibonacci, &user_arguments);
printf("Sum of fabonacci sequence is %d ", args->result) }While compiling, It gives the following error
invalid operands of types ‘void’ and ‘void’ to binary ‘operator+’
Please help in pointing what am i doing wrong here??
-
Return nothing from a function having return typeI have a class PackageSingleton and got a function getPackage whose return type is another class Package. This function iterates over a queue and retrieves a package and executes it. If a queue is empty i want to return nothing and keep looping the queue until a package is found. In C++ NULL cant be returned and returning a nullptr is giving an error
no viable conversion from returned value of type 'nullptr_t' to function return type 'Package
. Any idea how should i handle this situation.
c++
-
mapping pthread id to custom idI am planning to have more variable in the struct e.g.
struct thread_data {
int thread_id;
const char *message;
double result
};Richard MacCutchan wrote:
And why do you need to map the real thread id to some other value?
The application in which i am creating pthreads is a simulation environment on top of which my actual thread scheduling library will execute so the each pthread act like virtual core. Each core(pthread) has its own work package queue from which it retrieves the package for execution and when it is empty it attempts to steal from other cores(via work stealing method). Every core has a package manager singleton class which is responsible for adding and getting the package from the queue. In order to access the other cores(using the singleton class) i need the mapping so that whenever each core access the package manager class (and its queue), it do based on the custom id. I hope i explained it better this time
-
mapping pthread id to custom idAfter creating a pthread, i am setting the thread id to a custom id using a map.
pthread_t threads[noOfThreads];
struct thread_data td[noOfThreads];// a struct which only contains int thread_id
thread= pthread_create(&threads[i], NULL, startFunc, (void *)&td[i]);
setID(threads[i], td[i].thread_id);SetID function
setID(pthread_t pid, int id ){
thread_ids[pid]=id;// How can i access this value in getID function??definition of map
std::map thread_ids;
I want to get the mapped value based on the key value in the following function but dont know how to do exactly. getID function
getID() {
if (thread\_ids.find(pid) ==thread\_ids.end()) return -1; return thread\_ids\[pid\];//
}
I am very beginner so spare me if i am making a stupid mistake and please point that and help me correcting it
c++, pthread