简体   繁体   English

C pthreads错误

[英]C pthreads error

Programming Language C 编程语言C
below is the code that uses multiple threads to print out a file. 下面是使用多个线程来打印文件的代码。 There are no errors, however the code doesn't work correctly. 没有错误,但是代码无法正常运行。 However, when compiled it shows this warning 5 times: 'cast from pointer to integer of different size' 但是,在编译时会显示5次此警告:“从指针投射到不同大小的整数”

I've tried everything I can think of to resolve this issue, but haven't been success and now are just shooting in the dark. 我已经尽力想解决此问题,但还没有成功,现在只是在黑暗中进行拍摄。 Does anyone see where my mistake is? 有人看到我的错误在哪里吗? Any help is greatly appreciated and will gladly provide any other information upon request. 任何帮助将不胜感激,并将根据要求提供其他信息。

Thanks. 谢谢。

#include <sys/mman.h>
#include <sys/stat.h> 
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#define NUM_THREAD 4


struct fileParams {
     int fd;
     int size;
};

void *printFile(void *stuff)
{
     struct fileParams *params = stuff;      
     int addr;
     addr=(unsigned char *)mmap(NULL, (int) &params->size, PROT_READ, 
     MAP_PRIVATE,(int) &params->fd,0);
     write(STDOUT_FILENO, addr, (int)&params->size);
}

int main (int argc, char * argv[])
{
     pthread_t threads[NUM_THREAD];
     unsigned char *addr;
     int fd,rc;
     struct stat sb;
     int numCPU=sysconf(_SC_NPROCESSORS_ONLN);
     struct fileParams params;  

     printf("Number of aviable cores: %d\n",numCPU);
     printf("Using 4 processors\n");

     if (argc != 2 || strcmp(argv[1], "—help") == 0)
          printf("Usage: %s file\n", argv[0]);

     fd=open(argv[1],O_RDONLY);
     if (fd == -1)
     {
         printf("File open fdailed.\n");
    exit(EXIT_FAILURE);
     }

    if (fstat(fd, &sb) == -1)
    {
        printf ("fstat error\n");
        exit(EXIT_FAILURE);
    }
    params.fd=fd;
    params.size=sb.st_size/4;
    for (int n = 0; n<4; n++)
         rc=pthread_create(&threads[n],NULL,printFile,&params);

    exit(EXIT_SUCCESS);
    }

You need provide inputs to functions that match the function - passing pointers where integers are wanted (or the other way around) will generate warnings or errors depending on compile options. 您需要为与该函数匹配的函数提供输入-在需要整数的地方传递指针(或相反),这将根据编译选项生成警告或错误。

mmap takes an size_t as the 2nd parameter, but you are giving it a cast int to a pointer (&params->size), the same with mmaps 5th parameter. mmap将size_t作为第二个参数,但是您将其强制转换为指针(&params-> size)的整数,与mmaps第五个参数相同。

Get rid of the '&' so it is just a int. 摆脱掉“&”,它只是一个整数。

mmap also returns a void *, which you are then assigning to addr (an int). mmap还返回一个空*,然后将其分配给addr(一个int)。

Change int to a void * pointer type which should also fix the 5th warning. 将int更改为void *指针类型,该类型也应修复第5条警告。

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

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