linux单纯测试文件线程IO操作

#include <iostream>
#include <errno.h>
#include <inttypes.h>
#include <libgen.h>
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <unistd.h>
#include <pthread.h>
typedef int (*sock_callback_t)();
class BaseSo
{
public:
    BaseSo();
BaseSo(sock_callback_t fun):m_fun(fun){};
int run();
private:
    sock_callback_t m_fun;
};
BaseSo::BaseSo() 
{
}
int BaseSo::run()
{
    m_fun();
}

 struct mystruct {     
            int i;     
            char cha; 
            char shuzu[800000];
 };

static int callback()
{
  struct mystruct s; 
  s.cha = 'A';
 pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; 

 pthread_mutex_lock(&mutex1); 


 FILE *fp = fopen("test.txt","rb+");  
 fseek(fp,0L,SEEK_SET);
 fread(&s,sizeof(s),1,fp);
 s.i = s.i + 1;
 fseek(fp,0L,SEEK_SET);
 fwrite(&s,sizeof(s),1,fp);  
 fclose(fp);

 pthread_mutex_unlock(&mutex1); 
}
void *thread(void *ptr)
{
	   BaseSo basesock(callback);
	   basesock.run();

   return 0;
}
using namespace std;
int main()
{
  int i = 0;
  for(i =0; i<20000; i++)
  {
pthread_t id;
 int ret = pthread_create(&id, NULL, thread, NULL);
 pthread_join(id, NULL);



  } 
   FILE *stream;     
    struct mystruct s;     
    if ((stream = fopen("test.txt", "r")) == NULL) /* open file TEST.$$$ */    
    {         
        fprintf(stderr, "Cannot open output file.\n");         
        return 1;     
    }     
 fseek(stream,0L,SEEK_SET);
    fread(&s, sizeof(s), 1, stream); /* 写的struct文件*/    
    fclose(stream); /*关闭文件*/    
    printf("%d",s.i);
    printf("\n%c",s.cha);

}

  

posted on 2020-04-08 15:52  lydstory  阅读(289)  评论(0)    收藏  举报

导航