Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <time.h>
- float sum = 0;
- int n;
- int w;
- float *random_numbers;
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- void* array_sum(void* arg)
- {
- int start_index = *(int *) arg;
- float tmp_sum = 0;
- printf("Thread #%ld size=%d\n", pthread_self(), (n/w));
- for (int i = 0; i < n/w; i++)
- tmp_sum += random_numbers[start_index+i];
- pthread_mutex_lock(&mutex);
- sum += tmp_sum;
- pthread_mutex_unlock(&mutex);
- printf("Thread #%ld sum=%f\n", pthread_self(), tmp_sum);
- pthread_exit(NULL);
- }
- void* array_sum2(void* arg)
- {
- int start_index = *(int *) arg;
- float tmp_sum = 0;
- printf("Thread #%ld size=%d\n", pthread_self(), n - (w-1) * (n/w));
- for (int i = 0; i < n - (w-1) * (n/w); i++)
- tmp_sum += random_numbers[start_index+i];
- pthread_mutex_lock(&mutex);
- sum += tmp_sum;
- pthread_mutex_unlock(&mutex);
- printf("Thread #%ld sum=%f\n", pthread_self(), tmp_sum);
- pthread_exit(NULL);
- }
- int main(int argc, char **argv)
- {
- if (argc != 3)
- {
- printf("Nalezy podac dokladnie 2 argumenty do wywolania tego programu!\n");
- exit(-1);
- }
- if (atoi(argv[1]) >= 1000000)
- {
- printf("Za duze n!\n");
- exit(-2);
- }
- if (atoi(argv[2]) < 0 || atoi(argv[2]) > atoi(argv[1]))
- {
- printf("Niepoprawne w!\n");
- exit(-3);
- }
- n = atoi(argv[1]);
- w = atoi(argv[2]);
- random_numbers = malloc(n * sizeof(*random_numbers));
- /* Generate random numbers */
- srand(0);
- for (int i = 0; i < n; i++)
- random_numbers[i] = 1000. * rand() / RAND_MAX;
- /* Args to functions*/
- int arguments[w];
- arguments[0] = 0;
- for (int i = 1; i < w - 1; i++)
- arguments[i] = i*(n/w);
- arguments[w-1] = n - (n - (w-1) * (n/w));
- /* Threads version */
- pthread_t threads_ids[w];
- clock_t start = clock();
- for (int i = 0; i < w-1; i++)
- {
- pthread_create(&threads_ids[i], NULL, array_sum, &arguments[i]);
- }
- pthread_create(&threads_ids[w-1], NULL, array_sum2, &arguments[w-1]);
- for (int i = 0; i < w; i++)
- pthread_join(threads_ids[i], NULL);
- clock_t end = clock();
- printf("w/Threads: sum = %f, time = %f sec \n", sum, ((double) (end - start) / CLOCKS_PER_SEC));
- /* Without threads version */
- sum = 0;
- start = clock();
- for (int i = 0; i < n; i++)
- sum += random_numbers[i];
- end = clock();
- printf("wo/Threads: sum = %f, time = %f sec \n", sum, ((double) (end - start) / CLOCKS_PER_SEC));
- free(random_numbers);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement