gpt4 book ai didi

c - Ubuntu 上的 "__thread"

转载 作者:行者123 更新时间:2023-11-30 15:52:52 27 4
gpt4 key购买 nike

  • 嗨,我正在使用 C 库对机器人进行编程。阅读时代码中,我遇到了术语“_thread”,我不知道是什么是不是意味着.我试图搜索该项目,看看是否“_thread”上有任何定义,但没有意义大部头书。我猜下面的代码可能与我的问题有关。

我的问题是来自“static __thread Thread* threadData;”行和“__thread AssertFramework::Thread* AssertFramework::threadData = 0;”,你能猜出“__thread”是什么意思吗?它是类型吗?特殊函数的名称?指向线程的指针???

#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>
#include <cstring>
...
class AssertFramework
{
public:
struct Line
{
char file[128];
int line;
char message[128];
};

struct Track
{
Line line[16];
int currentLine;
bool active;
};

struct Thread
{
char name[32];
Track track[2];
};

struct Data
{
Thread thread[2];
int currentThread;
};

static pthread_mutex_t mutex;
static __thread Thread* threadData;

int fd;
Data* data;

AssertFramework() : fd(-1), data((Data*)MAP_FAILED) {}

~AssertFramework()
{
if(data != MAP_FAILED)
munmap(data, sizeof(Data));
if(fd != -1)
close(fd);
}

bool init(bool reset)
{
if(data != MAP_FAILED)
return true;

fd = shm_open("/bhuman_assert", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if(fd == -1)
return false;

if(ftruncate(fd, sizeof(Data)) == -1 ||
(data = (Data*)mmap(NULL, sizeof(Data), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == MAP_FAILED)
{
close(fd);
fd = -1;
return false;
}

if(reset)
memset(data, 0, sizeof(Data));

return true;
}

} assertFramework;

pthread_mutex_t AssertFramework::mutex = PTHREAD_MUTEX_INITIALIZER;
__thread AssertFramework::Thread* AssertFramework::threadData = 0;

最佳答案

这是 gcc 特定的 Thread-Local Storage 。请注意,C11 添加了 _Thread_local,C++11 添加了 thread_local 作为支持线程本地数据的标准方式。

关于c - Ubuntu 上的 "__thread",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14073168/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com