Skip to content

Instantly share code, notes, and snippets.

@cwvh
Created September 2, 2013 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cwvh/6408974 to your computer and use it in GitHub Desktop.
Save cwvh/6408974 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ccan/list/list.h>
struct context {
struct list_head connections;
int num_connections;
};
struct connection {
int id;
struct list_node list;
};
int main(int argc, char *argv[])
{
struct context ctx;
struct connection *conn;
list_head_init(&ctx.connections);
srand(time(NULL));
const int N = argc > 1 ? atoi(argv[1]) : 10;
/* Create a bunch of connections */
for (int i = 0; i < N; i++) {
conn = malloc(sizeof(*conn));
conn->id = i;
list_add(&ctx.connections, &conn->list);
ctx.num_connections++;
}
/* Simulate servicing connections by iterating
* down the list and randomly removing and inserting
* connections
*/
printf("%d\n", ctx.num_connections);
for (int i = 0; i < 10; i++) {
list_for_each(&ctx.connections, conn, list) {
if (rand()%23 == 0) {
list_del_from(&ctx.connections, &conn->list);
ctx.num_connections--;
}
}
list_for_each(&ctx.connections, conn, list) {
if (rand()%11 == 0) {
struct connection *new;
new = malloc(sizeof(*new));
new->id = 42;
list_add(&ctx.connections, &new->list);
ctx.num_connections++;
}
}
}
printf("%d\n", ctx.num_connections);
}
#include <iostream>
#include <vector>
#include <ctime>
struct connection {
int id;
};
struct context {
std::vector<connection> connections;
};
int main(int argc, char** argv)
{
context ctx;
srand(time(nullptr));
const int N = argc > 1 ? atoi(argv[1]) : 10;
for (int i = 0; i < N; i++)
ctx.connections.emplace_back(connection{i});
std::cout << ctx.connections.size() << '\n';
for (int i = 0; i < 10; i++) {
int removed = 0;
for (auto& conn : ctx.connections) {
if (rand()%23 == 0) {
conn = std::move(ctx.connections.back());
removed++;
}
}
ctx.connections.resize(ctx.connections.size() - removed);
const int n = ctx.connections.size();
for (int i = 0; i < n; i++) {
if (rand()%11 == 0)
ctx.connections.emplace_back(connection{i+n});
}
}
std::cout << ctx.connections.size() << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment