在 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");
}
上述超时看起来似乎不错,没有使用另外的线程,但是问题也非常大:
- 使用了全局变量
ctx
-
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中通过WithCancel
,WithDeadline
,WithTimeout
或WithValue
派生出新的context
,即实现上述C语言代码的功能。
- 更轻量级的
goroutine
, 而不是线程 - 当父
context
被取消时,其派生的所有context
都将取消 - 在子
goroutine
中可以使用select <-ctx.Done()
逻辑来检查状态 -
context
是并发安全的 - 提供更多的退出状态结果, 使用
Error()
方法来获取更详细的退出状态 - 不使用全局变量以及全局的信号处理
详细请参考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
使用也是类似,参考官方文档即可。
网友评论