Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <pthread.h>
- typedef struct {
- int a, b;
- } ThArg;
- int a, b, n;
- void *troutine(void *arg) {
- ThArg *thArg = (ThArg*)arg;
- printf("Processed [%d %d]\n", thArg->a, thArg->b);
- return NULL;
- }
- void *zalloc(int nmemb, int sz) {
- void *p = calloc(nmemb, sz);
- if (!p) {
- perror("");
- exit(1);
- }
- return p;
- }
- int main(void) {
- scanf("%d%d%d", &a, &b, &n);
- int numsPerTh = (b - a + 1) / n;
- pthread_t *threads = (pthread_t*)zalloc(n, sizeof(pthread_t));
- ThArg *thArgs = (ThArg*)zalloc(n, sizeof(ThArg));
- for (int r, i = 0; i < n; i++) {
- thArgs[i].a = a + i * numsPerTh;
- thArgs[i].b = (i == n - 1) ? b : thArgs[i].a + numsPerTh - 1;
- if ((r = pthread_create(&threads[i], NULL, troutine, &thArgs[i]))) {
- fprintf(stderr, "pthread_create error: %s", strerror(r));
- exit(-1);
- }
- }
- for (int r, i = 0; i < n; i++) {
- if ((r = pthread_join(threads[i], NULL))) {
- fprintf(stderr, "pthread_join error: %s", strerror(r));
- exit(-1);
- }
- }
- free(thArgs);
- free(threads);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement