繁体   English   中英

c 线程中无效的类型转换,void* 到 int

[英]Invalid type conversion in c threads, void* to int

首先我希望你们都安全。 我试图传递一个包含在 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;
}

这样做的理想方法是让线程知道它在创建时是哪个线程。 您可以通过将线程 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;
}

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

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

如果您需要发送任何其他信息,请创建一个struct来承载您需要的所有内容,而不是传递int

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM