1 #include "libmemcached/common.h"
2 #include "libmemcached/memcached_pool.h"
5 struct memcached_pool_st
13 uint32_t current_size
;
16 static memcached_return
mutex_enter(pthread_mutex_t
*mutex
)
20 ret
= pthread_mutex_lock(mutex
);
21 while (ret
== -1 && errno
== EINTR
);
23 return (ret
== -1) ? MEMCACHED_ERRNO
: MEMCACHED_SUCCESS
;
26 static memcached_return
mutex_exit(pthread_mutex_t
*mutex
) {
29 ret
= pthread_mutex_unlock(mutex
);
30 while (ret
== -1 && errno
== EINTR
);
32 return (ret
== -1) ? MEMCACHED_ERRNO
: MEMCACHED_SUCCESS
;
36 * Grow the connection pool by creating a connection structure and clone the
37 * original memcached handle.
39 static int grow_pool(memcached_pool_st
* pool
) {
40 memcached_st
*obj
= calloc(1, sizeof(*obj
));
44 if (memcached_clone(obj
, pool
->master
) == NULL
)
50 pool
->mmc
[++pool
->firstfree
] = obj
;
56 memcached_pool_st
*memcached_pool_create(memcached_st
* mmc
,
57 uint32_t initial
, uint32_t max
)
59 memcached_pool_st
* ret
= NULL
;
60 memcached_pool_st object
= { .mutex
= PTHREAD_MUTEX_INITIALIZER
,
61 .cond
= PTHREAD_COND_INITIALIZER
,
63 .mmc
= calloc(max
, sizeof(memcached_st
*)),
68 if (object
.mmc
!= NULL
)
70 ret
= calloc(1, sizeof(*ret
));
79 /* Try to create the initial size of the pool. An allocation failure at
80 * this time is not fatal..
82 for (unsigned int ii
=0; ii
< initial
; ++ii
)
83 if (grow_pool(ret
) == -1)
90 memcached_st
* memcached_pool_destroy(memcached_pool_st
* pool
)
92 memcached_st
*ret
= pool
->master
;
94 for (int xx
= 0; xx
<= pool
->firstfree
; ++xx
)
96 memcached_free(pool
->mmc
[xx
]);
101 pthread_mutex_destroy(&pool
->mutex
);
102 pthread_cond_destroy(&pool
->cond
);
109 memcached_st
* memcached_pool_pop(memcached_pool_st
* pool
,
111 memcached_return
*rc
)
113 memcached_st
*ret
= NULL
;
114 if ((*rc
= mutex_enter(&pool
->mutex
)) != MEMCACHED_SUCCESS
)
119 if (pool
->firstfree
> -1)
120 ret
= pool
->mmc
[pool
->firstfree
--];
121 else if (pool
->current_size
== pool
->size
)
125 *rc
= mutex_exit(&pool
->mutex
);
129 if (pthread_cond_wait(&pool
->cond
, &pool
->mutex
) == -1)
132 mutex_exit(&pool
->mutex
);
134 *rc
= MEMCACHED_ERRNO
;
138 else if (grow_pool(pool
) == -1)
140 *rc
= mutex_exit(&pool
->mutex
);
146 *rc
= mutex_exit(&pool
->mutex
);
151 memcached_return
memcached_pool_push(memcached_pool_st
* pool
,
154 memcached_return rc
= mutex_enter(&pool
->mutex
);
156 if (rc
!= MEMCACHED_SUCCESS
)
159 pool
->mmc
[++pool
->firstfree
]= mmc
;
161 if (pool
->firstfree
== 0 && pool
->current_size
== pool
->size
)
163 /* we might have people waiting for a connection.. wake them up :-) */
164 pthread_cond_broadcast(&pool
->cond
);
167 return mutex_exit(&pool
->mutex
);