【问题标题】:Invalid type conversion in c threads, void* to intc线程中的无效类型转换,void*到int
【发布时间】:2020-07-05 21:59:12
【问题描述】:

首先我希望你们都平安。我正在尝试传递一个数组,其中包含在 C 中创建的线程的 threadID。我知道程序充满了错误,但我遇到了一个我不知道如何解决的错误。在我写 threadID[i]=(int*)tid[i]; 的那一行我得到无效的类型转换。我在将 void* 转换为 int 时尝试做什么,我得到了那个错误。我的 C 语言很差,但我正在努力学习。如果我能得到任何帮助,我将不胜感激

谢谢

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

int x=0;


void* printMsg(void *tid)
{
    pthread_t id = pthread_self();
    int nthreads;
    //Get the number of threads
    nthreads= sizeof(tid);

    //Copy thread array from main to threadID array
    int *threadID[nthreads];
;
    for(int i=0;i<nthreads;i++)
        threadID[i]=(int*)tid[i];

    if(pthread_equal(id,threadID[x]))
    {
        printf("%d\n",x);
        x++;
    }
    while(1);
}

int main()
{
    int i=0;
    int n=0;

    printf("Enter number of threads : ");
    scanf("%d",&n);

    pthread_t tid[n];

    for(i=0;i<n;i++)
    {
        pthread_create(&(tid[i]), NULL, &printMsg, (void*)tid);
    }

    for (i=0;i<n;i++) 
    { 
        pthread_join(tid[i], NULL); 
    } 

    sleep(5);

    return 0;
}

【问题讨论】:

  • 因为我认为函数 printMsg 只能接受 void* 争论。 print 用于打印数字。基本上程序需要每个线程打印 var x 。因此,如果我想创建 10 个线程,第一个线程必须打印 1,第二个线程必须打印 2,依此类推
  • 最好将您希望代码执行的操作放入问题本身。此外,您不能在指针上使用sizeof(即可以,但结果不会是您所期望的)。 C 数组知道它们只是在其范围内的数组;一旦你将它们传递给一个函数,它们就会忘记大小,所以你必须自己记住大小。
  • 好的,谢谢,下次我会做的不好。如果我发现任何东西,我会做更多的挖掘和更新

标签: c unix type-conversion pthreads


【解决方案1】:

理想的方法是让线程在创建时知道它是哪个线程。您可以通过将线程 ID 作为参数传递来做到这一点。您可以通过以下方式做到这一点:

void *printMsg(void *tnum_p) {
    int tnum = *(int *)tnum_p;
    printf("%d\n", tnum);
    return NULL;
}

int main() {
    int i = 0;
    int n = 0;

    printf("Enter number of threads: ");
    scanf("%d", &n);

    pthread_t tid[n];
    int tnum[n];

    for(i = 0; i < n; i++) {
        tnum[i] = i;
        pthread_create(&(tid[i]), NULL, &printMsg, &(tnum[i]));
    }

    for (i = 0; i < n; i++) {
        pthread_join(tid[i], NULL);
    }

    return 0;
}

有人可能认为我们可以只传递&amp;i 而不是&amp;(tnum[i]);这将在没有任何错误的情况下编译,但是每个线程都会收到相同的地址,这取决于每个线程在那里找到的运气和时间(即你几乎肯定会有重复的数字)。

(我也更喜欢tid + i 和tnum + i 而不是&amp;(tid[i]) 和&amp;(tnum[i]),但这只是我。)

如果您需要发送任何其他信息,请发送struct 来携带您需要的所有信息,而不是传递int。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 2021-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多