Search pthreads. I'm new too. Here is a code snippet for a sum of 1 to 1,000,000,000 (also my first pthread work program).
#include <stdio.h> #include <pthread.h> struct arg { int a, b; int *rst; }; typedef struct arg arg; void* sum(void *); int main() { pthread_t sum1, sum2; int s1, s2; pthread_create(&sum1, NULL, sum, &(arg){1, 500000000, &s1}); pthread_create(&sum2, NULL, sum, &(arg){500000001, 1000000000, &s2}); pthread_join(sum1, NULL); pthread_join(sum2, NULL); printf("%d\n", s1 + s2); } void* sum(void *ptr) { int i, temp = 0; arg *x = ptr; for(i = x->a; i <= x->b; ++i) temp += i; *(x->rst) = temp; }
Zifei tong
source share