问题
I am learning about multi-thread programming right now, and I noticed that programs with synchronization implemented with mutex is extremely slow on Mac OS X, to the extent it is usually better to use single thread instead. I understand that there are much faster ways of synchronizing, but I still wonder why it is like this. For a simple time measurement, I wrote this program.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
pthread_mutex_t lock;
long s;
double cur_time() {
struct timeval tp[1];
gettimeofday(tp, NULL);
return tp->tv_sec + tp->tv_usec * 1.0E-6;
}
void * func(){
int n = 1000000;
while(n > 0){
pthread_mutex_lock(&lock);
s++;
n --;
pthread_mutex_unlock(&lock);
}
return 0;
}
void * thread_func(void * arg_){
return func();
}
int main(){
pthread_mutex_init(&lock,NULL);
s = 0;
int i;
pthread_t pids[3];
double t1 = cur_time();
for(i = 0; i < 3; i++){
pthread_create(&pids[i],NULL,thread_func,NULL);
}
for(i = 0; i < 3; i++){
pthread_join(pids[i],0);
}
printf("s = %ld\n",s);
double t2 = cur_time();
printf("Time consumed: %fs\n",t2 - t1);
}
This program ran for 11.022169 seconds on my MacBook Air (OS X El Capitan), which has 4GB RAM and a Intel Core i5 Dual Core 1.6GHz processor. It only ran for 0.493699 seconds on my another computer with Ubuntu 14.04, a 16GB RAM, and a Intel Core 17 Octal Core 2.4GHz processor. I understand that there is a significant difference in processing power between these two computers, but I would not expect the difference to be this huge. Besides, when using other locks, for example spinlocks, the difference is never this big.
I would be very grateful if someone could offer me some knowledge on the reason of this difference.
Added: I missed out something. I also compared spinlock and mutex on each OS respectively. While on Linux the spinlock is significantly slower than mutex with a large number of threads, on Mac OS X mutex is always much much slower.To the extent of difference by one or two digits.
回答1:
Mutexes by default on MacOS apparently are implemented as "fair" mutexes. The downside of this can be significantly reduced performance; see https://blog.mozilla.org/nfroyd/2017/03/29/on-mutex-performance-part-1/
Note that when Mozilla tried switching to FIRSTFIT on mac (which isn't documented!), we found problems that blocked it: https://bugzilla.mozilla.org/show_bug.cgi?id=1353787#c7
回答2:
On Linux, mutexes are generally implemented in terms of the futex system call. On OS X, locking is significantly more costly because it requires sending a message to the kernel. However, this is notoriously difficult to benchmark correctly, and I haven’t examined your code.
来源:https://stackoverflow.com/questions/33991644/why-is-performance-of-pthread-mutex-so-bad-on-mac-os-x-compared-to-linux