linux多核多进程访问文件示例程序(每个核上运行一个程序)

来源:互联网 发布:玩绝地求生网络延迟 编辑:程序博客网 时间:2024/06/11 05:05
#include <stdio.h>#include <stdlib.h>#include <sys/types.h>#include <sys/sysinfo.h>#include <errno.h>#include <unistd.h> #include <fcntl.h> #include <sys/stat.h>#define __USE_GNU#include <sched.h>#include <ctype.h>#include <string.h>#include <pthread.h>#define THREAD_MAX_NUM100int num;void *threadWrite(void *arg){cpu_set_t mask;cpu_set_t get;int *a = (int *)arg;printf("the a is :%d\n",*a);char buf2[]={"abcdefghijklmnopqrstuvwxyz"};  //要写入的信息int fd2 = open("test",O_RDWR);               //打开要写入的文件if(fd2 == -1){printf("open failed\n");return ;}printf("success fd = %d\n",fd2);CPU_ZERO(&mask);                      //清零maskCPU_SET(*a,&mask);                    //根据参出设置该进程运行在哪个核上(参数范围为0-3,因为有4个物理核)if(sched_setaffinity(0,sizeof(mask),&mask)==-1)    //设定程序运行在哪个核上{printf("warning:could not set CPU affinity,continuing...\n");}CPU_ZERO(&get);if(sched_getaffinity(0,sizeof(get),&get)==-1)              //读取在哪个核上运行的信息{printf("warning:could not get thread affinity,continuing...\n");}int i;for(i=0;i<num;i++){if(CPU_ISSET(i,&get)){printf("this thread %d is running processor:%d\n",i,i);}}while(1){pwrite(fd2,buf2,strlen(buf2),0);//往文件中写入,pwrtie为可以设定偏移位置,也就可以保证文件的大小sleep(1);}return NULL;}void *threadFun(void *arg){cpu_set_t mask;cpu_set_t get;int *a = (int *)arg;printf("the a is :%d\n",*a);char buf1[1000];                  //保存读取内容缓冲区int fd1 = open("vimrc_bak",O_RDWR);   //打开文件if(fd1 == -1){printf("open failed\n");return ;}printf("success fd = %d\n",fd1);CPU_ZERO(&mask);                  //同样时设置进程运行在哪个核上CPU_SET(*a,&mask);if(sched_setaffinity(0,sizeof(mask),&mask)==-1){printf("warning:could not set CPU affinity,continuing...\n");}CPU_ZERO(&get);if(sched_getaffinity(0,sizeof(get),&get)==-1){printf("warning:could not get thread affinity,continuing...\n");}int i;for(i=0;i<num;i++){if(CPU_ISSET(i,&get)){printf("this thread %d is running processor:%d\n",i,i);}}memset(buf1,0,sizeof(buf1));while(1){if(read(fd1,buf1,sizeof(buf1))>0)        //持续赋取文件内容,当读取到文件尾时,在从头开始{printf("buf = %s\n",buf1);memset(buf1,0,sizeof(buf1));sleep(1);}else{lseek(fd1,0,SEEK_SET);}}return NULL;}int main(){pthread_t thread[4];int tid[4];int i;num = sysconf(_SC_NPROCESSORS_CONF);    //获取物理核的具体数printf("system has %d processors\n",num);for(i=0;i<2;i++)   //创建进程{tid[i] = i;pthread_create(&thread[i],NULL,(void*)threadFun,(void*)&tid[i]);}for(i=2;i<4;i++)    //创建进程{tid[i] = i;pthread_create(&thread[i],NULL,(void*)threadWrite,(void*)&tid[i]);}for(i=0;i<4;i++)   //等待进程运行完毕后再退出{pthread_join(thread[i],NULL);}return 0;}


当时编写程序时的思路:

1,首先先写出来多进程的程序

2,在1的基础上把进程绑定到指定的物理核上

3,编写操作文件的读写函数

4,修改写函数,因为使用write函数持续写时,会导致文件随时间变的巨大,最后修改为pwrite

5,把两个程序结合到一起。