I'm experimenting with threads in C, and I'm confused upon some results.
I have the following loop:
for(size_t i=0;i<1000000000;i++){
a++;
}
It increments a global variable a. I've done this with 6 variables, a to e.
First, I incremented the variables consecutively in main:
#include<stdio.h>
#include<pthread.h>
size_t a,b,c,d,e,f;
int main(void){
for(size_t i=0;i<1000000000;i++){
a++;
}
for(size_t i=0;i<1000000000;i++){
b++;
}
for(size_t i=0;i<1000000000;i++){
c++;
}
for(size_t i=0;i<1000000000;i++){
d++;
}
for(size_t i=0;i<1000000000;i++){
e++;
}
for(size_t i=0;i<1000000000;i++){
f++;
}
size_t abcdef=a+b+c+d+e+f;
printf("%zu\n",abcdef);
return 0;
}
Then, when testing the program with time, the following results were given:
6000000000
real 0m11.450s
user 0m11.446s
sys 0m0.000s
I'd expect the results using pthreads to be quite a bit faster:
#include<stdio.h>
#include<pthread.h>
size_t a,b,c,d,e,f;
void *t1(void *args){
for(size_t i=0;i<1000000000;i++){
a++;
}
return NULL;
}
void *t2(void *args){
for(size_t i=0;i<1000000000;i++){
b++;
}
return NULL;
}
void *t3(void *args){
for(size_t i=0;i<1000000000;i++){
c++;
}
return NULL;
}
void *t4(void *args){
for(size_t i=0;i<1000000000;i++){
d++;
}
return NULL;
}
void *t5(void *args){
for(size_t i=0;i<1000000000;i++){
e++;
}
return NULL;
}
void *t6(void *args){
for(size_t i=0;i<1000000000;i++){
f++;
}
return NULL;
}
int main(void){
pthread_t p1,p2,p3,p4,p5,p6;
pthread_create(&p1,NULL,t1,NULL);
pthread_create(&p2,NULL,t2,NULL);
pthread_create(&p3,NULL,t3,NULL);
pthread_create(&p4,NULL,t4,NULL);
pthread_create(&p5,NULL,t5,NULL);
pthread_create(&p6,NULL,t6,NULL);
pthread_join(p1,NULL);
pthread_join(p2,NULL);
pthread_join(p3,NULL);
pthread_join(p4,NULL);
pthread_join(p5,NULL);
pthread_join(p6,NULL);
size_t abcdef=a+b+c+d+e+f;
printf("%zu\n",abcdef);
return 0;
}
However, the results were quite unexpecting:
6000000000
real 0m14.521s
user 1m26.048s
sys 0m0.014s
Not only is the real time larger, which I'd expect to be lower, but the user time is over 1 minute, which, I did not wait a minute.
What is happening here? How can I solve it?