logo

Parallelism vs Concurrency

#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #define THREAD_NUM 2 int primes[10] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; void* routine(void* arg) { int index = *(int*)arg; int sum = 0; sleep(1); for (int j = 0; j < 5; j++) { sum += primes[index + j]; } printf("Local sum: %d\n", sum); *(int*)arg = sum; return arg; } int main(int argc, char* argv[]) { pthread_t th[THREAD_NUM]; int i; for (i = 0; i < THREAD_NUM; i++) { int* a = malloc(sizeof(int)); *a = i * 5; if (pthread_create(&th[i], NULL, &routine, a) != 0) { perror("Failed to create thread"); } } int globalSum = 0; for (i = 0; i < THREAD_NUM; i++) { int* r; if (pthread_join(th[i], (void**) &r) != 0) { perror("Failed to join thread"); } globalSum += *r; free(r); } printf("Global sum: %d\n", globalSum); return 0; }
Course thumb

Unix Threads in C

Courses with this lesson