Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <math.h>
- typedef struct {
- int **startat;
- int *docount;
- } thread_arg;
- /* This is our thread function. It is like main(), but for a thread*/
- int *threadFunc(void *args)
- {
- thread_arg *aargs = args;
- int erg = 0;
- for (int i = 0; i < aargs->docount; ++i) {
- if(aargs->startat + i > erg) {
- erg = aargs->startat + i;
- }
- }
- free(aargs);
- return erg;
- }
- int main(void)
- {
- int length = 100;
- int in[length];
- for (int i = 0;i < length; ++i) {
- in[i] = rand();
- }
- int threads = (int) 1+sqrt(length-10); // we want to use sqrt(length) threads in an ideal szenario without slowdown when creating them. 10 is a threshhold for this
- int threadstepsize = (int) 1+length/threads;
- int ret = -1;
- pthread_t * thread = malloc(sizeof(pthread_t)*threads);
- for (int i = 0; i < threads; ++i) {
- thread_arg *args = malloc(sizeof *args);
- args->startat = in[i*threadstepsize];
- args->docount = &threadstepsize;
- ret = pthread_create(&thread[i], NULL, threadFunc, args);
- if(ret != 0) {
- printf ("Create pthread error!\n");
- exit (1);
- }
- }
- printf("main waiting for threads to terminate...\n");
- int out[threads];
- for (int i = 0; i < threads; ++i) {
- pthread_join(thread[i],out[i]);
- }
- thread_arg *args = malloc(sizeof *args);
- args->startat = &out;
- args->docount = &threads;
- int erg = threadFunc(args);
- printf("max is %d\n",erg);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement