__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;
}