__thread 变量使用

17 篇文章 0 订阅

__thread 使用规则:

  • 只能修饰POD类型, 不能修饰class类型, 因为无法自动调用构造函数和析构函数
  • __thread可以修饰全局变量和函数内的静态变量, 但是不能修饰函数的局部变量或者class的普通成员变量.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <string>

#define THREAD_COUNT 2

// 每个线程都会保留一份
__thread int g_number = 0;

pthread_mutex_t g_print_lock = PTHREAD_MUTEX_INITIALIZER;


// 使用c++完美转发对printf进行包装,以实现线程安全的打印
template <typename ...Ts>
void print_info(Ts &&...t)
{
    pthread_mutex_lock( &g_print_lock );
    printf(std::forward<Ts>(t)...);
    pthread_mutex_unlock( &g_print_lock );
}


void* work(void *pparams) 
{
    for(int i = 0;  i < 5; i++)
    {
        print_info("%d\n", g_number++);
        sleep(1);
    }

    return nullptr;
}

struct A
{
    // __thread int m_var;  // 不能修饰类的普通成员变量
};


int main()
{
    pthread_t thds[THREAD_COUNT];
    // pthread_attr_t *pthd_attr = nullptr;

    static __thread std::string* t_str = new std::string("hello"); // __thread可以修饰函数内的静态变量
    // __thread  int n = 0; // error,  不能修饰函数内容的普通局部变量


    for(int i = 0; i < THREAD_COUNT; i++)
    {
        pthread_create(&thds[i], nullptr, work ,nullptr);
        // pthread_detach(thd1);  // 分离线程, 线程结束后资源自动释放给系统, 而不需要其他线程join等待
    }


    // 等待线程结束
    print_info("waiting for sub-thread finishing\n");
    for(int i = 0; i < THREAD_COUNT; i++)
    {
        int iret = pthread_join(thds[i], nullptr );
        
        if(0 != iret)
        {
            if(EINVAL == iret)
                print_info("thread is not a joinalbe thread\n");
            else 
                print_info("pthread_join error: %d\n", iret);
            return 0;
        }
    
    }

    return 0;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值