I am starting to program in parallel, and I tried to write a parallel program with the pthread library. I ran the program on an 8-processor computer. The problem is that when I increase NumProcs, each thread slows down, although their tasks are always the same. Can someone help me figure out what's going on? `
#define MAX_NUMP 16
using namespace std;
int NumProcs;
pthread_mutex_t SyncLock;
pthread_cond_t SyncCV;
int SyncCount;
pthread_mutex_t ThreadLock;
struct timespec StartTime;
struct timespec EndTime;
void Barrier()
{
int ret;
pthread_mutex_lock(&SyncLock);
SyncCount++;
if(SyncCount == NumProcs) {
ret = pthread_cond_broadcast(&SyncCV);
assert(ret == 0);
} else {
ret = pthread_cond_wait(&SyncCV, &SyncLock);
assert(ret == 0);
}
pthread_mutex_unlock(&SyncLock);
}
void* ThreadLoop(void* tmp)
{
long threadId = (long) tmp;
int ret;
int startTime, endTime;
int count=0;
Barrier();
startTime = clock();
for(int i=0;i<65536;i++)
for(int j=0;j<1024;j++)
count++;
endTime = clock();
printf("threadid:%ld, time:%d\n",threadId,endTime-startTime);
}
int main(int argc, char** argv)
{
pthread_t* threads;
pthread_attr_t attr;
int ret;
int dx;
if(argc != 2) {
fprintf(stderr, "USAGE: %s <numProcesors>\n", argv[0]);
exit(-1);
}
assert(argc == 2);
NumProcs = atoi(argv[1]);
assert(NumProcs > 0 && NumProcs <= MAX_NUMP);
threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs);
assert(threads != NULL);
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
ret = pthread_mutex_init(&SyncLock, NULL);
assert(ret == 0);
ret = pthread_mutex_init(&ThreadLock, NULL);
assert(ret == 0);
ret = pthread_cond_init(&SyncCV, NULL);
assert(ret == 0);
SyncCount = 0;
Count = 0;
ret = clock_gettime(CLOCK_MONOTONIC, &StartTime);
for(dx=0; dx < NumProcs; dx++) {
ret = pthread_create(&threads[dx], &attr, ThreadLoop, (void*) dx);
assert(ret == 0);
}
for(dx=0; dx < NumProcs; dx++) {
ret = pthread_join(threads[dx], NULL);
assert(ret == 0);
}
ret = clock_gettime(CLOCK_MONOTONIC, &EndTime);
printf("Time = %ld nanoseconds\n", EndTime.tv_nsec - StartTime.tv_nsec);
pthread_mutex_destroy(&ThreadLock);
pthread_mutex_destroy(&SyncLock);
pthread_cond_destroy(&SyncCV);
pthread_attr_destroy(&attr);
return 0;
}
source
share