c - pthread_create 不工作。传递参数 3 警告

标签 c linux ubuntu pthreads

我正在尝试创建一个线程,根据我的内存,这应该是正确的方法:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5

int SharedVariable =0;
void SimpleThread(int which)
{
    int num,val;
    for(num=0; num<20; num++){
        if(random() > RAND_MAX / 2)
            usleep(10);
        val = SharedVariable;
        printf("*** thread %d sees value %d\n", which, val);
        SharedVariable = val+1;
    }
    val=SharedVariable;
    printf("Thread %d sees final value %d\n", which, val);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t< NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, SimpleThread, (void* )t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }

   /* Last thing that main() should do */
   pthread_exit(NULL);
}

我得到的错误是这个:

test.c: In function ‘main’: test.c:28: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type /usr/include/pthread.h:227: note: expected ‘void * (*)(void *)’ but argument is of type ‘void (*)(int)’

我无法更改 SimpleThread 函数,因此更改参数类型不是一个选项,即使我已经尝试过但它也不起作用。

我做错了什么?

最佳答案

SimpleThread 应该声明为

void* SimpleThread(void *args) {
}

当你向你的线程传递参数时,最好为它们定义一个struct,传递一个指向那个struct的指针作为void*,并转换回函数内的正确类型。

关于c - pthread_create 不工作。传递参数 3 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11253025/

相关文章:

c - ioctl() 用于 C 语言套接字编程

c++ - 'isprint' 在 solaris 上为不可打印的字符返回 true

ubuntu - Ubuntu 20.04 中的 Pyqt4

node.js - Node 未启动

c - OMAP3 上奇怪的 SD 卡是 omap_hsmmc 驱动程序吗?

c中的char指针导致段错误

linux - 如何永久存储文本模式浏览器的代理信息(例如链接)

MySQL 通过 SSH + Bash 错误

c++ - 错误: switch quantity not an integer switch ((MPI_Datatype) datatype){

在 ubuntu 中安装 Python pip