muduo 库解析之十二:ThreadLocal

TSD

在多线程程序中,所有线程共享程序中的变量。现在有一全局变量,所有线程都可以使用它,改变它的值。而如果每个线程希望能单独拥有它,那么就需要使用线程存储了。表面上看起来这是一个全局变量,所有线程都可以使用它,而它的值在每一个线程中又是单独存储的。这就是线程存储(Thread-specific Data,或称为 TSD)的意义。

#include <pthread.h>

int pthread_setspecific(pthread_key_t key, const void *value);
void *pthread_getspecific(pthread_key_t key);
int pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
int pthread_key_delete(pthread_key_t key);
  • 函数 pthread_key_create() 用来创建线程私有数据。该函数从 TSD 池中分配一项,将其地址值赋给 key 供以后访问使用。第 2 个参数是一个销毁函数,它是可选的,可以为 NULL,为 NULL 时,则系统调用默认的销毁函数进行相关的数据注销。如果不为空,则在线程退出时(调用 pthread_exit() 函数)时将以 key 关联的数据作为参数调用它,以释放分配的缓冲区,或是关闭文件流等。
  • 不论哪个线程调用了 pthread_key_create(),所创建的 key 都是所有线程可以访问的,但各个线程可以根据自己的需要往 key 中填入不同的值,相当于提供了一个同名而不同值的全局变量(这个全局变量相对于拥有这个变量的线程来说)。

测试一:

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

pthread_key_t key;

struct test_struct
{
    int i;
    float f;
};

void *worker1(void *arg)
{
    test_struct test{1, 3.14};
    pthread_setspecific(key, &test);
    printf("test addr is:%p
", &test);
    test_struct *addr = (test_struct *)pthread_getspecific(key);
    printf("worker1 pthread_getpecific(key) addr is:%p
", addr);
    printf("worker1 pthread_getspecific(key) test value is:{%d,%f}
", addr->i, addr->f);
    printf("------------------------------------------------------
");
}

void *worker2(void *arg)
{
    int temp = 20;
    sleep(2);
    printf("worker2 temp addr is:%p
", &temp);
    pthread_setspecific(key, &temp);
    int *addr = (int *)pthread_getspecific(key);
    printf("worker2 pthread_getpecific(key) addr is:%p
", addr);
    printf("worker2  pthread_getpecific(key) value is:%d
", *addr);
}

int main()
{
    pthread_t tid1, tid2;
    pthread_key_create(&key, NULL);
    pthread_create(&tid1, NULL, worker1, NULL);
    pthread_create(&tid2, NULL, worker2, NULL);
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_key_delete(key);

    return 0;
}

测试二:

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

pthread_key_t thread_log_key;

void write_to_thread_log(const char* message)
{
    FILE* thread_log = (FILE*)pthread_getspecific(thread_log_key);
    fprintf(thread_log,"%s
",message);
}

void close_thread_log(void* thread_log)
{
    fclose((FILE*)thread_log);
}

void *thread_function(void* args)
{
    char thread_log_filename[128];
    char thread_start_message[128];
    FILE* thread_log;

    sprintf(thread_log_filename,"thread%u.log",(unsigned int)pthread_self());
    thread_log = fopen(thread_log_filename,"w");
    pthread_setspecific(thread_log_key,thread_log);
    sprintf(thread_start_message,"thread %u starting",(unsigned int)pthread_self());
    write_to_thread_log(thread_start_message);
    pthread_exit(NULL);
}

int main()
{
    int i;
    pthread_t threads[5];
    pthread_key_create(&thread_log_key,close_thread_log);
    for(int i = 0;i < 5;++i)
        pthread_create(&threads[i],NULL,thread_function,NULL);

    for(i = 0;i < 5;++i)
        pthread_join(threads[i],NULL);

    return 0;
}

源码

ThreadLocal.h

#pragma once

#include "Mutex.h"
#include "NonCopyable.h"

namespace muduo
{
    template<typename T>
    class ThreadLocal : NonCopyable
    {
    public:
        ThreadLocal()
        {
            MCHECK(pthread_key_create(&pkey_,&ThreadLocal::destructor));
        }

        ~ThreadLocal()
        {
            MCHECK(pthread_key_delete(pkey_));
        }

        T& value()
        {
            T* per_thread_value = static_cast<T*>(pthread_getspecific(pkey_));
            if(!per_thread_value)
            {
                T* new_obj = new T();
                MCHECK(pthread_setspecific(pkey_,new_obj));
                per_thread_value = new_obj;
            }
            return *per_thread_value;
        }

    private:
        static void destructor(void* x)
        {
            T* obj = static_cast<t*>(x);
            typedef char T_must_be_complete_type[sizeof(T) == 0 ? -1 : 1];
            T_must_be_complete_type dummy;
            (void)dummy;
            delete obj;
        }

    private:
        pthread_key_t pkey_;
    };
}
原文地址:https://www.cnblogs.com/xiaojianliu/p/14702040.html