【发布时间】: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) ¶ms->size, PROT_READ,
MAP_PRIVATE,(int) ¶ms->fd,0);
write(STDOUT_FILENO, addr, (int)¶ms->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,¶ms);
exit(EXIT_SUCCESS);
}
【问题讨论】:
-
...以及警告的行号我将留给读者作为练习...
-
在
printFile:int addr; addr=(unsigned char *)stuff; -
你应该得到一些警告。你为什么不理他们?那是 C 101。
-
尝试像这样转换
struct fileParams *params = stuff;:struct fileParams *params = (struct fileParams*)stuff;并尝试在pthread_create中更改&params,像这样:(void*) params
标签: c multithreading pthreads