+static int get_connection(SimpleStore *store)
+{
+ int fd = -1;
+
+ g_mutex_lock(store->fd_pool_lock);
+ if (!g_queue_is_empty(store->fd_pool)) {
+ fd = GPOINTER_TO_INT(g_queue_pop_head(store->fd_pool));
+ }
+ g_mutex_unlock(store->fd_pool_lock);
+ if (fd != -1)
+ return fd;
+
+ fd = socket(PF_INET, SOCK_STREAM, 0);
+ if (fd < 0) {
+ g_warning("Error creating simplestore socket: %m");
+ return -1;
+ }
+
+ if (connect(fd, (struct sockaddr *)&store->server_addr,
+ sizeof(store->server_addr)) < 0) {
+ g_warning("Error connecting to simplestore server: %m");
+ return -1;
+ }
+
+ return fd;
+}
+
+static void put_connection(SimpleStore *store, int fd)
+{
+ g_mutex_lock(store->fd_pool_lock);
+ g_queue_push_head(store->fd_pool, GINT_TO_POINTER(fd));
+ while (g_queue_get_length(store->fd_pool) > MAX_IDLE_CONNECTIONS) {
+ fd = GPOINTER_TO_INT(g_queue_pop_tail(store->fd_pool));
+ close(fd);
+ }
+ g_mutex_unlock(store->fd_pool_lock);
+}
+