golang context

在 go1.7 及以上版本 context 包被正式列入官方库中,所以我们只需要import "context"就可以了,而在 go1.6 及以下版本,我们要import "golang.org/x/net/context"
为什么需要context呢?
我们可以看一下在linux下使用C语言实现的cancel context

#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

typedef struct cancel_context
{
  int is_exit;
  // pthread_mutex_t mutex;
  pthread_rwlock_t rwlock;
} cancel_context_t;

void *thr_fn(void *arg)
{
  cancel_context_t *p_ctx = (cancel_context_t *) arg;
  if(p_ctx == NULL) pthread_exit((void *)-1);

  int is_exit;
  int cnt = 0;
  while(1)
  {
    // pthread_mutex_lock(&p_ctx->mutex);
    pthread_rwlock_rdlock(&p_ctx->rwlock);
    is_exit = p_ctx->is_exit;
    // pthread_mutex_unlock(&p_ctx->mutex);
    pthread_rwlock_unlock(&p_ctx->rwlock);

    if(is_exit) break;

    printf("thr_fn is busing, %d\n", ++cnt);
    usleep(100);
  }

  printf("thr_fn, cancelled by exit_fn\n");
  pthread_exit((void *)0);
}

void *cancel_fn(void *arg)
{
  cancel_context_t *p_ctx = (cancel_context_t *) arg;
  if(p_ctx == NULL) pthread_exit((void*)-1);

  usleep(1000);

  // pthread_mutex_lock(&p_ctx->mutex);
  pthread_rwlock_wrlock(&p_ctx->rwlock);
  p_ctx->is_exit = 1;
  // pthread_mutex_unlock(&p_ctx->mutex);
  pthread_rwlock_unlock(&p_ctx->rwlock);

  printf("thr_fn, you need to exit\n");
  pthread_exit((void *)0);
}

void main()
{
  int err;
  pthread_t p_id, cancel_p_id;
  void *ret;
  Context ctx;
  ctx.is_exit = 0;
  // pthread_mutex_init(&ctx.mutex, NULL);
  pthread_rwlock_init(&ctx.rwlock, NULL);

  err = pthread_create(&p_id, NULL, thr_fn, (void *) &ctx);
  err = pthread_create(&cancel_p_id, NULL, cancel_fn, (void *) &ctx);

  pthread_join(p_id, NULL);
  pthread_join(cancel_p_id, NULL);

  // pthread_mutex_destroy(&ctx.mutex);
  pthread_rwlock_destroy(&ctx.rwlock);

  printf("main thread exit!!!\n");
}

在上面的实现(非最好实现)中,我们使用了一个线程来实现cancel的功能,在该线程中先sleep要等待的时间(模拟某个在做完某一件事之后来设置thr_fn的退出状态)。同时在thr_fn中不断地去检查这个退出状态。这种方法有很多缺陷,首先需要不断的去检查退出状态;其次对于某些阻塞非超时调用不适用。
接下来看看在linux下使用C语言实现的timeout context

#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>

typedef struct timeout_context
{
  int is_exit;
  pthread_rwlock_t rwlock;
} timeout_context_t;

timeout_context_t ctx;

void *thr_fn(void *arg)
{
  timeout_context_t *p_ctx = (timeout_context_t *) arg;
  if(p_ctx == NULL) pthread_exit((void *)-1);

  int is_exit;
  int cnt = 0;
  while(1)
  {
    pthread_rwlock_rdlock(&p_ctx->rwlock);
    is_exit = p_ctx->is_exit;
    pthread_rwlock_unlock(&p_ctx->rwlock);

    if(is_exit) break;

    printf("thr_fn is busing, %d\n", ++cnt);
    usleep(1000 * 100);
  }

  printf("thr_fn, cancelled by timer\n");
  pthread_exit((void *)0);
}

void timer(int sig)
{
  if(SIGALRM == sig)
  {
    pthread_rwlock_wrlock(&ctx.rwlock);
    ctx.is_exit = 1;
    pthread_rwlock_unlock(&ctx.rwlock);

    printf("timeout\n");
  }

  return;
}

void main()
{
  int err;
  pthread_t p_id;

  ctx.is_exit = 0;
  pthread_rwlock_init(&ctx.rwlock, NULL);

  signal(SIGALRM, timer);
  alarm(2);

  err = pthread_create(&p_id, NULL, thr_fn, (void *) &ctx);

  pthread_join(p_id, NULL);

  pthread_rwlock_destroy(&ctx.rwlock);

  printf("main thread exit!!!\n");
}

上述超时看起来似乎不错,没有使用另外的线程,但是问题也非常大:

  1. 使用了全局变量ctx
  2. alarm方法只能精确到秒级别

那么,忽略使用全局变量的问题,我们对上述代码进行改良来解决时间精确度的问题。

#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>

typedef struct timeout_context
{
  int is_exit;
  pthread_rwlock_t rwlock;
} timeout_context_t;

timeout_context_t ctx;

void *thr_fn(void *arg)
{
  timeout_context_t *p_ctx = (timeout_context_t *) arg;
  if(p_ctx == NULL) pthread_exit((void *)-1);

  int is_exit;
  int cnt = 0;
  while(1)
  {
    pthread_rwlock_rdlock(&p_ctx->rwlock);
    is_exit = p_ctx->is_exit;
    pthread_rwlock_unlock(&p_ctx->rwlock);

    if(is_exit) break;

    printf("thr_fn is busing, %d\n", ++cnt);
    usleep(100);
  }

  printf("thr_fn, cancelled by timer\n");
  pthread_exit((void *)0);
}

void timer(int sig)
{
  if(SIGALRM == sig)
  {
    pthread_rwlock_wrlock(&ctx.rwlock);
    ctx.is_exit = 1;
    pthread_rwlock_unlock(&ctx.rwlock);

    printf("timeout\n");
  }

  return;
}


void main()
{
  int err;
  pthread_t p_id;

  ctx.is_exit = 0;
  pthread_rwlock_init(&ctx.rwlock, NULL);

  signal(SIGALRM, timer);

  struct itimerval tick;
  bzero(&tick, sizeof(tick));

  tick.it_value.tv_sec = 0;
  tick.it_value.tv_usec = 1000;

  // tick.it_interval.tv_sec = 0;
  // tick.it_interval.tv_usec = 1000;

  err = pthread_create(&p_id, NULL, thr_fn, (void *) &ctx);

  setitimer(ITIMER_REAL, &tick, NULL);

  pthread_join(p_id, NULL);

  pthread_rwlock_destroy(&ctx.rwlock);

  printf("main thread exit!!!\n");
}

使用了signal + settimer来实现,可以精确到微妙级别。
似乎还不错,但是在现实中,并发控制远非如此简单。如果在thr_fn中有创建了新的线程,同时也要求被创建的新线程需要先于父线程退出以保证资源的正确释放。那么只要在父线程退出前等待子线程退出即可,并且需要向子线程传递context,代码如下:

#include <pthread.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>

typedef struct timeout_context
{
  int is_exit;
  pthread_rwlock_t rwlock;
  timeout_context_t *parent;
} timeout_context_t;

timeout_context_t ctx;

void *child_thr_fn(void *arg)
{
  timeout_context_t *p_ctx = (timeout_context_t *) arg;
  if(p_ctx == NULL) pthread_exit((void *)-1);

  int is_exit;
  int cnt = 0;
  while(1)
  {
    pthread_rwlock_rdlock(&p_ctx->rwlock);
    is_exit = p_ctx->is_exit;
    pthread_rwlock_unlock(&p_ctx->rwlock);

    if(is_exit) break;

    printf("child_thr_fn is busing, %d\n", ++cnt);
    usleep(100);
  }

  printf("child_thr_fn, cancelled by timer\n");
  pthread_exit((void *)0);
}


void *parent_thr_fn(void *arg)
{
  timeout_context_t *p_ctx = (timeout_context_t *) arg;
  if(p_ctx == NULL) pthread_exit((void *)-1);

  int err;
  pthread_t p_id;
  err = pthread_create(&p_id, NULL, child_thr_fn, (void *) p_ctx);

  int is_exit;
  int cnt = 0;
  while(1)
  {
    pthread_rwlock_rdlock(&p_ctx->rwlock);
    is_exit = p_ctx->is_exit;
    pthread_rwlock_unlock(&p_ctx->rwlock);

    if(is_exit) break;

    printf("parent_thr_fn is busing, %d\n", ++cnt);
    usleep(100);
  }

  pthread_join(p_id, NULL);
  printf("parent_thr_fn, cancelled by timer\n");
  pthread_exit((void *)0);
}

void timer(int sig)
{
  if(SIGALRM == sig)
  {
    pthread_rwlock_wrlock(&ctx.rwlock);
    ctx.is_exit = 1;
    pthread_rwlock_unlock(&ctx.rwlock);

    printf("timeout\n");
  }

  return;
}


void main()
{
  int err;
  pthread_t p_id;

  ctx.is_exit = 0;
  pthread_rwlock_init(&ctx.rwlock, NULL);

  signal(SIGALRM, timer);

  struct itimerval tick;
  bzero(&tick, sizeof(tick));

  tick.it_value.tv_sec = 0;
  tick.it_value.tv_usec = 1000;

  // tick.it_interval.tv_sec = 0;
  // tick.it_interval.tv_usec = 1000;

  err = pthread_create(&p_id, NULL, parent_thr_fn, (void *) &ctx);

  setitimer(ITIMER_REAL, &tick, NULL);

  pthread_join(p_id, NULL);

  pthread_rwlock_destroy(&ctx.rwlock);

  printf("main thread exit!!!\n");
}

基于以上代码,我们也可以实现deadline context
下面看看value context的实现(可以用来实现基于请求的上下文数据传递,key/value上下文), 由于C语言没有相关Hashmap库,此处使用了c_hashmap

#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>

#include "hashmap.h"

#define KEY_MAX_LENGTH (256)
#define VALUE_MAX_LENGTH (1024*1024)
#define KEY_COUNT (1024*1024)

typedef struct value_context
{
  map_t h;
} value_context_t;

typedef struct data
{
  char key[KEY_MAX_LENGTH];
  int n;
  double d;
  char s[VALUE_MAX_LENGTH];
} data_t;

void value_context_init(value_context_t *p_ctx)
{
  assert(p_ctx != NULL);

  p_ctx->h = hashmap_new();
}

void value_context_set_int(value_context_t *p_ctx, char *key, int n)
{
  data_t *data = malloc(sizeof(data_t));
  memcpy(data->key, key, strlen(key));
  data->n = n;

  hashmap_put(p_ctx->h, data->key, data);
}

void value_context_set_double(value_context_t *p_ctx, char *key, double d)
{
  data_t *data = malloc(sizeof(data_t));
  memcpy(data->key, key, strlen(key));
  data->d = d;

  hashmap_put(p_ctx->h, data->key, data);
}

void value_context_set_string(value_context_t *p_ctx, char *key, char *s)
{
  data_t *data = malloc(sizeof(data_t));
  memcpy(data->key, key, strlen(key));
  int len = strlen(s);
  memcpy(data->s, s, len > VALUE_MAX_LENGTH ? VALUE_MAX_LENGTH : len);

  hashmap_put(p_ctx->h, data->key, data);
}

int value_context_get_int(value_context_t *p_ctx, char *key)
{
  assert(p_ctx != NULL);
  data_t* value = NULL;
  hashmap_get(p_ctx->h, key, (void**)(&value));
  assert(value != NULL);
  return value->n;
}

double value_context_get_double(value_context_t *p_ctx, char *key)
{
  assert(p_ctx != NULL);
  data_t* value = NULL;
  hashmap_get(p_ctx->h, key, (void**)(&value));
  assert(value != NULL);
  return value->d;
}

char* value_context_get_string(value_context_t *p_ctx, char *key)
{
  assert(p_ctx != NULL);
  data_t* value = NULL;
  hashmap_get(p_ctx->h, key, (void**)(&value));
  assert(value != NULL);
  return value->s;
}

void filter(value_context_t *p_ctx)
{
  value_context_set_string(p_ctx, "username", "zouqilin");
}

void handler(value_context_t *p_ctx)
{
  char *s = value_context_get_string(p_ctx, "username");
  printf("context get username: %s\n", s);
}

void main()
{
  value_context_t ctx;
  value_context_init(&ctx);

  filter(&ctx);
  handler(&ctx);

  // here we need to free resource
}

上面代码实现了在handler处理之前调用了filter并在其中设置了username,因此在handler处理时可以拿到该设置的值。
如此绕了一大圈来说明golang加入的context的必要性。下面来说明context在并发编程和请求处理中的优势。
golang中通过WithCancelWithDeadlineWithTimeoutWithValue派生出新的context,即实现上述C语言代码的功能。

  1. 更轻量级的goroutine, 而不是线程
  2. 当父context被取消时,其派生的所有context都将取消
  3. 在子goroutine中可以使用select <-ctx.Done()逻辑来检查状态
  4. context是并发安全的
  5. 提供更多的退出状态结果, 使用Error()方法来获取更详细的退出状态
  6. 不使用全局变量以及全局的信号处理

详细请参考golang context,官方对每一种context都提供了使用例子。
下面使用golang来实现cancel context, 看看是如何代码是如何简洁和紧凑。

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    ctx, cancel := context.WithCancel(context.Background())

    go func(ctx context.Context) {
        defer wg.Done()
        n := 0
        for {
            select {
            case <-ctx.Done():
                return
            default:
                n++
                fmt.Printf("f is busing, %v\n", n)
                time.Sleep(1000 * time.Nanosecond)
            }
        }
    }(ctx)

    time.Sleep(5000 * time.Nanosecond)
    cancel()

    wg.Wait()
}

实现跟C语言相同的cancel context相当轻松,并且上述使用了时间精度为纳秒级别。
其他的context使用也是类似,参考官方文档即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,458评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,030评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,879评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,278评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,296评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,019评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,633评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,541评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,068评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,181评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,318评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,991评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,670评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,183评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,302评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,655评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,327评论 2 358

推荐阅读更多精彩内容

  • 什么是context 从go1.7开始,golang.org/x/net/context包正式作为context包...
    天唯阅读 12,623评论 3 26
  • 原文链接:http://studygolang.com/articles/5131 简介## Context是一个...
    雲凌禹阅读 4,817评论 0 2
  • 起因 最近学习golang框架的时候发现许多地方都用到了context的概念,比如grpc请求 etcd访问等许...
    Kathent阅读 1,650评论 0 3
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,678评论 18 139
  • 现在有很多人觉悟,看了不少管理自己时间、目标的书,包括我。 最近我却发现了一个极其好用的小方法(具体哪...
    起床困難户阅读 385评论 0 0