【问题标题】:Invalid Conversion int* to int while attempting to get p_thread id to int尝试将 p_thread id 转换为 int 时将 int* 无效转换为 int
【发布时间】:2020-10-07 02:53:57
【问题描述】:

对于我正在编写的一些代码,我正在尝试获取线程,但我不断收到错误消息。我正在用 Visual Studio 代码在 linux 上编程。

这是代码:

void* start(void *s) {
    int me = (int*)s;
    //int me = pthread_self();
    printf("Entered: %d\n", me);

    Lock(me);

    printf("TEST 1");
    for (int i = 0; i<MAX; i++) ans++;
    printf("TEST 2");

    Unlock(me);
    printf("TEST 3");

    return NULL;
}


pthread_create(&thread1, NULL, start, (void*)0);
pthread_create(&thread2, NULL, start, (void*)1);

pthread 创建在 main 方法中。我得到的错误:

错误:从“int*”到“int”的无效转换[-fpermissive] 49 |诠释我=(诠释*)s; | ^~~~~~~ | | |整数*

【问题讨论】:

    标签: c++ linux gcc


    【解决方案1】:

    int* 是指向值的指针,而不是值本身。您已将一个值转换为指针传递,您应该将其转换回一个值:

    int me = reinterpret_cast<int>(s);
    

    【讨论】:

    • 从我看到的例子(这是彼得森算法)他们这样做。我仍在学习,并不精通在 linux 上编程 c++。此外,当我尝试您的代码时,我得到一个类似的转换错误:错误:从“void*”转换为“int”失去精度 [-fpermissive] 49 | int me = reinterpret_cast(s); |
    • 示例必须在pthread_create 中传递与您不同的参数。如果它因精度损失而失败(在 64 位计算机上),您可以将其 reinterpret_cast 发送到 ptrdiff_t
    • 我已经解决了我的问题:((int)(&s));是我需要使用的。我使用了这个线程:stackoverflow.com/questions/1640423/… 来找出问题所在。我确实尝试了其他一些尝试,但我必须更好地了解出了什么问题,目前我有点困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2019-06-18
    • 1970-01-01
    • 2016-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多