|
| 1 | +#include "lib_acl.h" |
| 2 | +#include <stdio.h> |
| 3 | +#include <stdlib.h> |
| 4 | +#include "fiber/libfiber.h" |
| 5 | + |
| 6 | +typedef struct { |
| 7 | + ACL_FIBER_MUTEX *locks[2]; |
| 8 | +} MUTEX_CTX; |
| 9 | + |
| 10 | +static void fiber_main(ACL_FIBER *fb, void *arg) |
| 11 | +{ |
| 12 | + MUTEX_CTX *ctx = (MUTEX_CTX*) arg; |
| 13 | + ACL_FIBER_MUTEX *lock = ctx->locks[acl_fiber_id(fb) % 2]; |
| 14 | + |
| 15 | + acl_fiber_mutex_lock(lock); |
| 16 | + printf("fiber-%d lock %p ok\r\n", acl_fiber_self(), lock); |
| 17 | + |
| 18 | + acl_fiber_sleep(1); |
| 19 | + |
| 20 | + lock = ctx->locks[(acl_fiber_id(fb) + 1) % 2]; |
| 21 | + |
| 22 | + printf("fiber-%d begin to lock %p\r\n", acl_fiber_self(), lock); |
| 23 | + acl_fiber_mutex_lock(lock); |
| 24 | + printf("fiber-%d lock %p ok\r\n", acl_fiber_self(), lock); |
| 25 | +} |
| 26 | + |
| 27 | +static void *thread_main(void *arg) |
| 28 | +{ |
| 29 | + MUTEX_CTX *ctx = (MUTEX_CTX*) arg; |
| 30 | + |
| 31 | + sleep(1); |
| 32 | + printf("thread-%lu begin to lock %p\r\n", pthread_self(), ctx->locks[0]); |
| 33 | + acl_fiber_mutex_lock(ctx->locks[0]); |
| 34 | + printf("thread-%lu lock %p ok\r\n", pthread_self(), ctx->locks[0]); |
| 35 | + |
| 36 | + printf("thread-%lu begin to lock %p\r\n", pthread_self(), ctx->locks[1]); |
| 37 | + acl_fiber_mutex_lock(ctx->locks[1]); |
| 38 | + printf("thread-%lu lock %p ok\r\n", pthread_self(), ctx->locks[1]); |
| 39 | + |
| 40 | + return NULL; |
| 41 | +} |
| 42 | + |
| 43 | +static void fiber_profile(ACL_FIBER *fb, void *ctx) |
| 44 | +{ |
| 45 | + (void) fb; |
| 46 | + (void) ctx; |
| 47 | + |
| 48 | + while (1) { |
| 49 | + sleep(1); |
| 50 | + printf("\r\n"); |
| 51 | + acl_fiber_mutex_profile(); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +static void usage(const char *procname) |
| 56 | +{ |
| 57 | + printf("usage: %s -h [help]\r\n", procname); |
| 58 | +} |
| 59 | + |
| 60 | +int main(int argc, char *argv[]) |
| 61 | +{ |
| 62 | + int ch; |
| 63 | + MUTEX_CTX ctx; |
| 64 | + pthread_t tid; |
| 65 | + |
| 66 | + ctx.locks[0] = acl_fiber_mutex_create(0); |
| 67 | + ctx.locks[1] = acl_fiber_mutex_create(0); |
| 68 | + |
| 69 | + while ((ch = getopt(argc, argv, "h")) > 0) { |
| 70 | + switch (ch) { |
| 71 | + case 'h': |
| 72 | + usage(argv[0]); |
| 73 | + return 0; |
| 74 | + default: |
| 75 | + break; |
| 76 | + } |
| 77 | + } |
| 78 | + |
| 79 | + acl_fiber_create(fiber_main, &ctx, 32000); |
| 80 | + acl_fiber_create(fiber_main, &ctx, 32000); |
| 81 | + acl_fiber_create(fiber_profile, NULL, 32000); |
| 82 | + |
| 83 | + pthread_create(&tid, NULL, thread_main, &ctx); |
| 84 | + |
| 85 | + acl_fiber_schedule(); |
| 86 | + |
| 87 | + acl_fiber_mutex_free(ctx.locks[0]); |
| 88 | + acl_fiber_mutex_free(ctx.locks[1]); |
| 89 | + |
| 90 | + pthread_join(tid, NULL); |
| 91 | + return 0; |
| 92 | +} |
0 commit comments