我正在尝试学习如何使用 POSIX 线程在 C 中编写并行算法。我的环境是带有 gcc 4 的 Mac OS X 10.5.5。
编译:
gcc -Wall -D_REENTRANT -lpthread source.c -o test.o
所以,我的问题是,如果我在 Ubuntu 9.04 机器中编译它,它会以线程顺序顺利运行,在 Mac 上看起来互斥锁不起作用,线程不会等待获取共享信息。
苹果电脑:
#1
#0
#2
#5
#3
#4
ubuntu
#0
#1
#2
#3
#4
#5
有任何想法吗?
按照下面的源代码:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#define NUM_THREADS 6
pthread_mutex_t mutexsum;
pthread_t threads[NUM_THREADS];
long Sum;
void *SumThreads(void *threadid){
int tmp;
int i,x[10],y[10];
// Para cada x e y do vetor, jogamos o valor de i, só para meio didáticos
for (i=0; i<10 ; i++){
x[i] = i;
y[i] = i;
}
tmp = Sum;
for (i=0; i<10 ; i++){
tmp += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
Sum += tmp;
printf("Im thread #%ld sum until now is: %ld\n",threadid,Sum);
pthread_mutex_unlock (&mutexsum);
return 0;
}
int main(int argc, char *argv[]){
int i;
Sum = 0;
pthread_mutex_init(&mutexsum, NULL);
for(i=0; i<NUM_THREADS; i++){
pthread_create(&threads[i], NULL, SumThreads, (void *)i);
}
pthread_exit(NULL);
}