pthread_create不起作用。传递参数3警告

时间:2012-06-28 21:16:00

标签: 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:在函数'main'中:test.c:28:警告:传递参数3   来自不兼容指针类型的'pthread_create'   /usr/include/pthread.h:227:注意:预期'void *(* )(void * )'但是   参数的类型为'void(*)(int)'

我无法更改SimpleThread函数,因此即使我已经尝试过也无法更改参数类型,但它也无法正常工作。

我做错了什么?

2 个答案:

答案 0 :(得分:13)

SimpleThread应声明为

void* SimpleThread(void *args) {
}

当您将参数传递给线程时,最好为它们定义struct,将指针传递给struct作为void*,并在内部转换回正确的类型功能。

答案 1 :(得分:3)

这是你的程序的编译和“工作”版本,虽然我不得不承认不知道它正在做什么。对于观众中的评论家,我最后为pthread_join循环道歉。

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

#define NUM_THREADS 5

struct my_thread_info {
    long which;
};

int SharedVariable = 0;

void *SimpleThread(void *data)
{
    int num, val;
    struct my_thread_info *info = data;

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

    val = SharedVariable;
    printf("Thread %ld sees final value %d\n", info->which, val);

    free(info);
    return NULL;
}

int main(int argc, char *argv[])
{
    pthread_t threads[NUM_THREADS];
    int rc;
    long t;
    struct my_thread_info *info;
    for (t = 0; t < NUM_THREADS; t++) {
        printf("In main: creating thread %ld\n", t);

        info = malloc(sizeof(struct my_thread_info));
        info->which = t;

        rc = pthread_create(&threads[t], NULL, SimpleThread, info);
        if (rc) {
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    for (t = 0; t < NUM_THREADS; t++) {
        pthread_join(threads[t], NULL);
    }
}