多线程(二):更复杂一点的程序 (三)

2014-11-24 01:38:53 · 作者: · 浏览: 7
= pMyTest->dataNum;
pthread_mutex_lock(pMyTest->pMutIndex);
index = pMyTest->index[0];
pMyTest->index[0]++;
pthread_mutex_unlock(pMyTest->pMutIndex);
while(index < dataNum) {
input = pMyTest->input[index];
output = calculate(input);
printf("index=%3u, input=%8u, output=%2u, threadID=%2u\n", index, input, output, threadID);
pMyTest->output[index] = output;
pthread_mutex_lock(pMyTest->pMutIndex);
index = pMyTest->index[0];
pMyTest->index[0]++;
if(output == 0) {
pMyTest->primeNum[0]++;
}
pthread_mutex_unlock(pMyTest->pMutIndex);
}
pthread_exit(NULL);
}

int main(void) {
int i, ret;
int threadNum = 2;
myTest * pMyTest = (myTest *)malloc(sizeof(myTest));
pMyTest->dataNum = 100;
pMyTest->input = (int *)malloc(sizeof(int)*pMyTest->dataNum);
pMyTest->output = (int *)malloc(sizeof(int)*pMyTest->dataNum);
for(i=0; idataNum;++i) {
if(i % 4 == 0)
pMyTest->input[i] = (1 << (i%30)) + 1;
else
pMyTest->input[i] = (7 << (i%16)) + 1;
}
pMyTest->index = (int *)calloc(1, sizeof(int));
pMyTest->primeNum = (int *)calloc(1, sizeof(int));

pMyTest->pMutIndex = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(pMyTest->pMutIndex, NULL);

pMyTest->threadNum = threadNum;
myTest * inMyTest = (myTest *)malloc(sizeof(myTest)*threadNum);
for(i=0; i memcpy(inMyTest+i, pMyTest, sizeof(myTest));
(inMyTest+i)->threadID = i;
}
pthread_t * tid = (pthread_t*)malloc(sizeof(pthread_t)*threadNum);
printf("Begin create pthread.\n");
for(i=0; i ret = pthread_create(tid+i, NULL, (void *)thread, (myTest *)(inMyTest+i));
if(ret != 0) {
printf("Create pthread error.\n");
return 0;
}
}
for(i=0; i pthread_join(tid[i], NULL);
printf("素数个数:%d\n", pMyTest->primeNum[0]);
free(tid);
free(inMyTest);
pthread_mutex_destroy(pMyTest->pMutIndex);
free(pMyTest->pMutIndex);
free(pMyTest->input);
free(pMyTest->output);
free(pMyTest->index);
free(pMyTest->primeNum);
free(pMyTest);
return 0;
}