Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
LD_PRELOAD and thread local variable

I have a shared library (libtest.cpp) and a simple program (test.cpp). I want them to share a thread local variable gVar. The shared library is linked through LD_PRELOAD.

Here is my code for the shared library libtest.cpp:

#include<stdio.h>

__thread int gVar;

void print_gVar(){
  printf("%d\n", gVar);
}

Below is the code for test.cpp.

#include<stdio.h>

__thread int gVar;

void __attribute__((weak)) print_gVar();

int main(){
  gVar = 10;
  print_gVar(); 
  return 0;
}

And I use the following script to compile and run them.

g++ -g -shared -fPIC -olibtest.so libtest.cpp
g++ -g -fPIC -o test test.cpp
LD_PRELOAD=./libtest.so ./test

The expected result is 10 because the assignment in test.cpp will affect the gVar in libtest.cpp. However, I only got 0. It seems that the the gVar in libtest.cpp and the gVar in test.cpp are not linked.

I did some additional tests:

If I add __attribute__((weak)) to the declaration of gVar in any of the files, the output is still 0.

If I remove __thread from both files, then the result is 10 (successful).

If I add extern and __attribute__((weak)) to the declaration of gVar in libtest.cpp, there will be segmentation fault.

I guess there must be something wrong with LD_PRELOAD and __thread. But I cannot figure out.

Could anyone tell me how I can make it work? Thank you very much!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

This is not possible, since thread-local-storage requires per-thread initialisation.

LD_PRELOAD will load the library even before the standard library is loaded, which messes up TLS initialisation.

Update:

Please read sections 2 and 3 of ELF Handling For Thread-Local Storage

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda