-
-
Save cwvh/6408974 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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