pthread_create中使用的参数出错

时间:2018-03-21 04:37:11

标签: c parameters pthreads

我正在处理以下pthread程序,该程序查找string2中字符串中的子串数:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define NUM_THREADS 4
#define MAX 1024

int n1,n2,i;
char *s1,*s2;
FILE *fp;

char *substring(char *string, int position, int length);
void occurrence();


int readf(FILE *fp)
{
    if((fp=fopen("strings.txt", "r"))==NULL){
        printf("ERROR: can't open strings.txt!\n");
        return 0;
    }
    s1=(char *)malloc(sizeof(char)*MAX);
    if(s1==NULL){
        printf("ERROR: Out of memory!\n");
        return -1;
    }
    s2=(char *)malloc(sizeof(char)*MAX);
    if(s1==NULL){
        printf("ERROR: Out of memory\n");
        return -1;
    }
    /*read s1 s2 from the file*/
    s1=fgets(s1, MAX, fp);
    s2=fgets(s2, MAX, fp);
    n1=strlen(s1);  /*length of s1*/
    n2=strlen(s2)-1; /*length of s2*/
    if(s1==NULL || s2==NULL || n1<n2)  /*when error exit*/
        return -1;
}

int main(void)
{
    pthread_t tid;
    pthread_create(&tid, NULL, occurrence, NULL);
    pthread_join(tid, NULL);
    exit(0);

}

char *substring(char *string, int position, int length)
{
    char *pointer;
    int c;

    pointer = malloc(length+1);

    if (pointer == NULL)
    {
        printf("Unable to allocate memory.\n");
        exit(1);
    }

    for (c = 0 ; c < length ; c++)
    {
        *(pointer+c) = *(string+position-1);
        string++;
    }

    *(pointer+c) = '\0';

    return pointer;
}

void occurrence()
{
    char *string1;
    char *string2;
    char *new_str;
    int counter=0;
    readf(fp);

    string1 = s1;
    string2 = s2;
    new_str = malloc(200);
    for(i=1;i<=strlen(string1);i++)
    {
        new_str = substring(string1,i,strlen(string2));
        if(strcmp(new_str, string2)==0)
        {
            counter++;
        }
    }
    printf("The number of substrings is: %d",counter);
}

当我编译并运行它时,它运行正常,但我收到以下警告:

|44|warning: passing argument 3 of 'pthread_create' from incompatible pointer type|
|314|note: expected 'void * (*)(void *)' but argument is of type 'void (*)()'|

我知道它与用于Pthread的参数有关,但是我无法弄清楚如何修复它。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

线程函数必须遵循特定的签名。即使您没有使用参数并且不返回值,您仍必须拥有正确的签名。

如果您不需要参数,请忽略它。

如果您没有特定的返回值,请返回NULL

答案 1 :(得分:0)

只需让occurence函数接受一个void*参数,警告就会消失。