【问题标题】:C pthreads errorC pthreads 错误
【发布时间】:2017-07-27 18:55:55
【问题描述】:

编程语言 C
下面是使用多个线程打印出文件的代码。没有错误,但是代码无法正常工作。但是,编译时会显示此警告 5 次: '从指针转换为不同大小的整数'

我已经尝试了我能想到的一切来解决这个问题,但没有成功,现在只是在黑暗中拍摄。有谁知道我的错误在哪里?非常感谢任何帮助,并很乐意应要求提供任何其他信息。

谢谢。

#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);
    }

【问题讨论】:

  • ...以及警告的行号我将留给读者作为练习...
  • printFile: int addr; addr=(unsigned char *)stuff;
  • 你应该得到一些警告。你为什么不理他们?那是 C 101。
  • 尝试像这样转换struct fileParams *params = stuff;struct fileParams *params = (struct fileParams*)stuff; 并尝试在pthread_create 中更改&amp;params,像这样:(void*) params

标签: c multithreading pthreads


【解决方案1】:

您需要为与函数匹配的函数提供输入 - 传递需要整数的指针(或相反)将根据编译选项生成警告或错误。

mmap 将 size_t 作为第二个参数,但您将其转换为指针 (&params->size),与 mmaps 的第五个参数相同。

去掉 '&' 所以它只是一个 int。

mmap 还返回一个 void *,然后将其分配给 addr(一个 int)。

将 int 更改为 void * 指针类型,它也应该修复第 5 个警告。

【讨论】:

    猜你喜欢
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2011-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多