我試圖使用聯合,以便我可以更新一個線程中的字段,然後在另一個線程中讀取allfields。在實際系統中,我有互斥體來確保一切安全。問題出在fieldB之前,我必須改變它,fieldB被聲明爲A和C字段。但是,由於第三方驅動程序的原因,fieldB必須與頁邊界進行分配。當我將字段B更改爲與valloc分配時,我遇到了問題。關於工會和堆分配內存的問題
問題: 1)有沒有辦法在頁面邊界上靜態聲明fieldB已被分配。基本上和valloc做同樣的事情,但是在堆棧上?
2)當字段B或任何字段在堆上分配時,是否可以進行聯合?不知道這是否合法。
這是我正在試驗的一個簡單的測試程序。除非你聲明fieldB類似於字段A和C,並且在公共方法中做出明顯改變,否則這是行不通的。
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
class Test
{
public:
Test(void)
{
// field B must be alligned to page boundary
// Is there a way to do this on the stack???
this->field.fieldB = (unsigned char*) valloc(10);
};
//I know this is bad, this class is being treated like
//a global structure. Its self contained in another class.
unsigned char* PointerToFieldA(void)
{
return &this->field.fieldA[0];
}
unsigned char* PointerToFieldB(void)
{
return this->field.fieldB;
}
unsigned char* PointerToFieldC(void)
{
return &this->field.fieldC[0];
}
unsigned char* PointerToAllFields(void)
{
return &this->allFields[0];
}
private:
// Is this union possible with field B being
// allocated on the heap?
union
{
struct
{
unsigned char fieldA[10];
//This field has to be alligned to page boundary
//Is there way to be declared on the stack
unsigned char* fieldB;
unsigned char fieldC[10];
} field;
unsigned char allFields[30];
};
};
int main()
{
Test test;
strncpy((char*) test.PointerToFieldA(), "", 10);
strncpy((char*) test.PointerToFieldB(), "1234567890", 10);
strncpy((char*) test.PointerToFieldC(), "2345678901", 10);
char dummy[11];
dummy[10] = '\0';
strncpy(dummy, (char*) test.PointerToFieldA(), 10);
printf("%s\n", dummy);
strncpy(dummy, (char*) test.PointerToFieldB(), 10);
printf("%s\n", dummy);
strncpy(dummy, (char*) test.PointerToFieldC(), 10);
printf("%s\n", dummy);
char allFields[31];
allFields[30] = '\0';
strncpy(allFields, (char*) test.PointerToAllFields(), 30);
printf("%s\n", allFields);
return 0;
}
根據您的來電valloc它看起來像你的意思是包含在'價值fieldB'必須頁面對齊。是對的嗎?無論如何,我能想到的任何解決方案都會浪費多達PAGE_SIZE - 1個字節,這是一堆浪費的堆棧。你爲什麼想把它分配到堆棧上? – torak 2010-08-26 21:34:00
你是對的,fieldB需要頁面對齊。我想沒有必要在堆棧上分配。我只是好奇,如果有可能?當所有東西都分配在堆棧上時,它似乎工作。當我使用valloc時,我得到了一個可怕的崩潰。如果你有一個解決方案,一切都在堆上,我打開了。 – 2010-08-26 21:43:20