c++

Linked List

roland's picture
Probably the most common C++ linked list structure is:


struct Node {
Node() { val = 0; Next = NULL; }
int val;
Node *Next;
};
Say you want to construct a list from 1 to 10


Node* construct_list() {
Node *head = new Node;
Node *p = head;
for(int i = 1; i <= 10; i++) {
p->val = i;
p->Next = new Node;
p = p->Next;
}
return head;
}

And now say you want to print the list you created.


void print(Node* head) {
Node *p = head;
while(p->Next != NULL) {
cout << p->val << " ";
p = p->Next;
}
}
Finally, say you want to get reversed copy of the linked list efficiently.


Node* reverse(Node* head) {
Node *iterator = head;
Node *new_head = new Node;

while (iterator->Next != NULL) {
Node *copy = new Node;
copy->val = iterator->val;
copy->Next = new_head;
new_head = copy;
iterator = iterator->Next;
}
return new_head;
}

Semaphores + Fork + Linux in C++

roland's picture

So, I waisted over a week trying to figure out shared memory semaphores in linux.

The only way semaphores are shared in memory is by giving them names and then doing a sem_open to open the memory address. Then you use sem_init to initialize.

There's another way of working the shared memory; that is using mmap.

The way mmap works is:

int file_descriptor = open( ... );
write(filename, sem_t something, 1); /// This is a bit weird. You write binary data to a file
unlink(filename);

then mmap(.... pass fd=file_descriptor... )

This will make sem_t available to all processes that have been forked.

Now, I didn't try it with mmap this particular example, but i have made a linked list with mmap.

It seems I finally understood how mmap works. Basically, you can write a size of N of something (Node *) in memory. Then you can iterate through each object and place pointers accordingly.

Syndicate content