1952740-Lab 3
1952740-Lab 3
1952740-Lab 3
Lab 3
Full name : Trịnh Mạnh Hùng
Student id: 1952740
4.1. Questions:
Code :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <time.h>
Result:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <string.h>
#include <math.h>
#include <time.h>
#define NUM_OF_THREADS 3
void *cal1(void* tid) {
int *n = (int *)tid;
double * count = (double *)malloc(sizeof(double));
*count = 0;
//printf("so: %d\n", *n);
for(int i = 0; i < *n; ++i) {
double rand_x = (double) rand()/RAND_MAX;
double rand_y = (double) rand()/RAND_MAX;
double z = rand_x * rand_x + rand_y * rand_y;
if(z <= 1) *count += 1;
}
//printf("%d, %f\n", *n, *count);
pthread_exit((void *)count);
}
void * result;
int numOfPoints = atoi(argv[1]);
if(numOfPoints < 0) {
printf("numberOfPoints: %d must >= 0\n", numOfPoints);
return -1;
}
int phandu = numOfPoints % NUM_OF_THREADS,
thuong = (numOfPoints/NUM_OF_THREADS);
int rc;
// request time
clock_t begin = clock();
double total_in_circle = 0;
pthread_t thread[NUM_OF_THREADS+1];
for(int i= 0; i <= NUM_OF_THREADS; ++i) {
if(i == NUM_OF_THREADS) {
rc = pthread_create(&thread[i], NULL, cal1, &phandu);
if(rc) {
printf("ERROR! pthread_create() is %d\n", rc);
exit(-1);
}
}
else {
rc = pthread_create(&thread[i], NULL, cal1, &thuong);
if(rc) {
printf("ERROR! pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_join(thread[i], &result);
total_in_circle += *(double *)result;
}
Result:
Problem 2:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
Result: