Skip to content

Instantly share code, notes, and snippets.

@antirez
Created January 13, 2016 11:26
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 antirez/ca7f47d62516b0206cf6 to your computer and use it in GitHub Desktop.
Save antirez/ca7f47d62516b0206cf6 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define C_OK 1
#define C_ERR 0
typedef struct clusterNode {
struct clusterNode **slaves;
int numslaves;
} clusterNode;
int clusterNodeRemoveSlave(clusterNode *master, clusterNode *slave) {
int j;
for (j = 0; j < master->numslaves; j++) {
if (master->slaves[j] == slave) {
if ((j+1) < master->numslaves) {
int remaining_slaves = (master->numslaves - j) - 1;
memmove(master->slaves+j,master->slaves+(j+1),
(sizeof(*master->slaves) * remaining_slaves));
}
master->numslaves--;
return C_OK;
}
}
return C_ERR;
}
int clusterNodeAddSlave(clusterNode *master, clusterNode *slave) {
int j;
/* If it's already a slave, don't add it again. */
for (j = 0; j < master->numslaves; j++)
if (master->slaves[j] == slave) return C_ERR;
master->slaves = realloc(master->slaves,
sizeof(clusterNode*)*(master->numslaves+1));
master->slaves[master->numslaves] = slave;
master->numslaves++;
return C_OK;
}
void showSlaves(clusterNode *n) {
int j;
for (j = 0; j < n->numslaves; j++) {
printf("%d) %p\n", j, (void*) n->slaves[j]);
}
}
int main(void) {
clusterNode *n = malloc(sizeof(*n));
n->numslaves = 0;
n->slaves = NULL;
srand(time(NULL)+getpid());
int j;
for(j=0; j < 1000000; j++) {
int r = (rand() % 5)+1;
if (rand() & 1)
clusterNodeAddSlave(n,(void*)(long)r);
else
clusterNodeRemoveSlave(n,(void*)(long)r);
}
showSlaves(n);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment