多线程计算----pthread

 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>

#define NUM_THREADS 10 
#define buffer_size 6000000

void *thread_function(void *agr);
int buffer[buffer_size];
int result[NUM_THREADS];
int result1[NUM_THREADS];

int main() {
	int res;
	pthread_t a_thread[NUM_THREADS];
	void *thread_result;
	int lots_of_threads;
	//static int buffer[60];
	int i, m;
	int tmp1;
	int flag = 1;
	struct timeval tv_start, tv_end;
	//static int result[10];

	for(i = 0; i < buffer_size; i++) {
		buffer[i] = (int)rand() % 10000;
	}

	gettimeofday(&tv_start, NULL);
	for(i = 0; i < NUM_THREADS; i++) {
		tmp1 = 0;
		for(m = 0; m < buffer_size / NUM_THREADS; m++){
			if(tmp1 < buffer[i * 10 + m])
				tmp1 = buffer[i * 10 + m];
		}
		result1[i] = tmp1;
	}
	gettimeofday(&tv_end, NULL);
	printf("Cost Time: %0.10fms\n", (float)((1000000 * (tv_end.tv_sec - tv_start.tv_sec) + tv_end.tv_usec - tv_start.tv_usec)/1000));

	for(lots_of_threads = 0; lots_of_threads < NUM_THREADS; lots_of_threads++) {
		res = pthread_create(&(a_thread[lots_of_threads]), NULL, thread_function, (void*)lots_of_threads);
		if(res != 0) {
			perror("Thread creation failed");
			exit(EXIT_FAILURE);
		}
		//sleep(1);
	}
	printf("Waiting for threads to finish.....\n");
	for(lots_of_threads = NUM_THREADS - 1; lots_of_threads >= 0; lots_of_threads--) {
		res = pthread_join(a_thread[lots_of_threads], &thread_result);
		if(res == 0) {
			printf("Picked up a thread\n");
		} else {
			perror("Pthread_join failed");
		}
	}

	for(m = 0; m < NUM_THREADS; m++) {
		if(result[m] != result1[m])
			flag = 0;
	}

  if(!flag)
		printf("Compute wrong~~~\n");
	else
		printf("Successful~~~\n");
	
	printf("All done\n");
}

void *thread_function(void *arg) {
	//int my_number = *(int*) arg;
	int my_number = (int)arg;
	int rand_num;
	int k;
  int tmp = 0;
	struct timeval tv_start, tv_end;


  gettimeofday(&tv_start, NULL);
	for(k = 0; k < buffer_size / NUM_THREADS; k++) {
		if(tmp < buffer[my_number * (buffer_size / NUM_THREADS) + k])
			tmp = buffer[my_number * (buffer_size / NUM_THREADS) + k];
	}

	result[my_number] = tmp;

	gettimeofday(&tv_end, NULL);
	printf("Thread %d Cost Time: %0.10fms\n", my_number, (float)((1000000 * (tv_end.tv_sec - tv_start.tv_sec) + tv_end.tv_usec - tv_start.tv_usec)/1000));

	printf("thread_function is running. Argument was %d\n", my_number);
	//rand_num = 1 + (int)(9.0 * rand() / (RAND_MAX + 1.0));
	//sleep(rand_num);
	//printf("Rand number %d\n", rand_num);
	//printf("Byte from %d\n", my_number);
	pthread_exit(NULL);
}



你可能感兴趣的:(pthread)