我正在将C ++源与C源和C ++源链接。我使用pthread(取消点)创建了一个线程,然后通过C或C ++源文件调用pthread_exit。

如果pthread_exit调用来自C源,则取消处理程序不会触发!这可能是什么原因?

b.cc:

#include <cstdio>
#include <cstdlib>
#include <stdbool.h>
#include <pthread.h>


extern "C" void V();
extern "C" void Vpp();
extern "C" void Vs();

#define PTHREAD_EXIT Vs





void cleanup(void*v)
{
    fprintf(stderr, "Aadsfasdf\n");
    exit(0);
}


void* f(void*p)
{
    pthread_cleanup_push(cleanup, NULL);
    PTHREAD_EXIT();
    pthread_cleanup_pop(true);

    return NULL;
}

int main()
{
    pthread_t p;
    if (pthread_create(&p, NULL, f, NULL))
        abort();
    for(;;);
}


vpp.cc:

#include <pthread.h>

extern "C" void Vpp();
void Vpp() {
    pthread_exit(0);
}


v.c:

#include <pthread.h>

void V() {
    pthread_exit(0);
}


vs.s:

.text
Vs: .global Vs
    call pthread_exit
    spin: jmp spin


与编译

g++ -c vpp.cc -g -o vpp.o -Wall
gcc -c v.c -g -o v.o -Wall
as vs.s -o vs.o
g++ b.cc vpp.o v.o vs.o -o b -lpthread -g -Wall


如果PTHREAD_EXIT为Vpp,程序将显示一条消息并终止,如果为V或Vs,则程序不会终止。

V和Vpp的反汇编是相同的,并且在V和Vpp之间更改PTHREAD_EXIT的定义仅在反汇编中的call Vcall Vpp之间更改。

编辑:
在另一台计算机上无法重现,所以我猜我在库中或其他方面遇到了错误。

最佳答案

我不知道,但是您正在给取消处理程序C ++链接。如果同时使用C链接会发生什么呢?

extern "C"
{
  void cleanup(void*v) { ... }
}

关于c++ - 如果从C源而不是C++源调用pthread_exit,取消处理程序将无法运行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1199336/

10-11 22:40
查看更多