I wrote a multithreaded program two multiply to matrices for an assignment, but when I run it it doesn't give me the results I expect. I set it up so that the threads would do the rows in order, using a mutex to keep them seperate:And the thread creation code looks like:Code:void *matmult(void *ptr) { int i, j; static int count = -1; ++count; while (rowcount < m - 1) { pthread_mutex_lock(&mutex); if (rowcount < m - 1) ++rowcount; else { pthread_mutex_unlock(&mutex); return NULL; } pthread_mutex_unlock(&mutex); printf("thread %d running\n",count); for (i = 0; i < k; ++i) { C[rowcount][i] = 0; for (j = 0; j < n; ++j) C[rowcount][i] += B[rowcount][j] * A[j][i]; } } }This seems like it should split the work evenly between all the threads, but when I run it I get output like:Code:pthread_t *tid = new pthread_t[numthreads]; for (i = 0; i < numthreads; ++i) pthread_create(&tid[i],NULL,matmult,NULL); for (i = 0; i < numthreads; ++i) pthread_join(tid[i],NULL);I don't really understand why this is happening. Is it because each row takes very little time to process, or because I'm not creating them with the right attributes, or what?thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 0 running
thread 1 running
thread 2 running
thread 3 running
thread 4 running
thread 5 running
thread 6 running
thread 7 running
thread 8 running
thread 9 running
thread 10 running



LinkBack URL
About LinkBacks


