【问题标题】:What is the proper way to call pthread_join() using dynamically loaded pthread library使用动态加载的 pthread 库调用 pthread_join() 的正确方法是什么
【发布时间】:2015-10-30 18:31:15
【问题描述】:

遇到了这个段错误,我似乎无法绕过它。将其缩小到pthread_join() 函数。我正在动态加载 libpthread。

int main(int argc, char **argv) 
{
    void *lib_handle;
    create pthread_c;
    join pthread_j;
    pthread_t thrd_id;

    int rc;
    char *error;

    lib_handle = dlopen("/lib/x86_64-linux-gnu/libpthread.so.0", RTLD_NOW);

    if (!lib_handle) 
    {
        fprintf(stderr, "%s\n", dlerror());
        exit(1);
    }

    pthread_c = dlsym(lib_handle, "pthread_create");
    pthread_j = dlsym(lib_handle, "pthread_join");

    if ((error = dlerror()) != NULL)  
    {
        fprintf(stderr, "%s\n", error);
        exit(1);
    }

    rc = pthread_c(&thrd_id, NULL, sub, (void *)NULL);
    pthread_j(thrd_id, NULL);  // CAUSES SEGFAULT
    printf ("testing");

    dlclose(lib_handle);
    return 0;
}

void* sub (void* a)
{
    printf("Hello Thread, I'm the World!\n");
}

printf() 语句显示pthread_create() 正在正常工作。但是我需要调用pthread_join(),否则程序会在线程启动之前终止。

【问题讨论】:

    标签: pointers segmentation-fault pthreads function-pointers dynamic-loading


    【解决方案1】:

    事实证明,您必须声明连接并创建 typedef 以使用 pthread_t 而不是 sys/types.h 中的 int

    typedef int (*create)(pthread_t, void*, void*, void*);
    typedef void (*join) (pthread_t, void*);
    

    我认为我使用 int 进行创建,它有效,但不适用于 join()

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 2013-05-24
      相关资源
      最近更新 更多