linux c thread

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>
#include <limits.h>
//编译命令:g++ -g -o multithread multithread-2.c -lpthread
const char *FILE_PATH="/root/test";
const int file_size[]={512,1024,46900};

struct args
{
	int max;
	int min;
};

void* work( void*);

int main()
{
	//printf("%s\n",FILE_PATH);
	printf("starting.........\n");
	
	int array_length=sizeof(file_size)/sizeof(file_size[0]);
	
	pthread_t* ids=(pthread_t*)malloc(sizeof(pthread_t)*array_length);
	
	int ret,i;
	
	struct args* arg;

	for( i=0;i<array_length;i++)
	{

		 arg=(struct args*)malloc(sizeof(struct args));
		
		if(i==0)
		{
			arg->max =file_size[0];
			arg->min = 0;
		}
		else
		{
			arg->max=file_size[i];
			arg->min=file_size[i-1];
		}
		

		ret=pthread_create(&ids[i],NULL,work,arg);
		
		if(ret!=0)
		{   
			printf ("Create pthread error!\n");
	                exit (1);
	        } 
	}
	
	for(int i=0;i<array_length;i++)
	{
		pthread_join(ids[i],0);
	}

	free(ids);
	free(arg);

	printf("ending.........\n");
	return 0;
}

void* work(void* parameter)
{
	args *arg=(args*)parameter;
	
	printf("this is a thread:[min-max]=%d-%d,id=%d\n",arg->min,arg->max,pthread_self());
	struct timeval* tv=(struct timeval*)malloc(sizeof(struct timeval));
	struct timezone* tz=(struct timezone*)malloc(sizeof(struct timezone));
	gettimeofday(tv,tz);
	
	printf("%d\n",tv->tv_sec);
	printf("%d\n",tv->tv_usec);
	
	char* char1=(char*)malloc(1000);
	sprintf(char1,"%d%d",tv->tv_sec,tv->tv_usec);
	printf("time:%s\n",char1);
	
	srand((unsigned)atoi(char1));
	
	int i;
	
	for(i=0;i<10;i++)
	{
		long int _rand =rand();
		printf("seed:%d\n",_rand);
		int bs=_rand%(arg->max-arg->min)+arg->min+1;
		printf("random:%d\n",bs);
		sprintf(char1,"dd if=/dev/zero of=%s/test.%d.%d.bin count=10 bs=%d\n",FILE_PATH,i,bs,bs);
		printf("%s\n",char1);
		//system(char1);
	}

	free(tv);
	free(tz);
	free(char1);

}

你可能感兴趣的:(thread)