{
int threadID;
int threadNum;
int dataNum;
int *input;
int *output;
int *index;
int *primeNum;
pthread_mutex_t *pMutIndex;
}myTest;
int calculate(int input) {
int i;
int output = 0;
for(i=2; i if(input % i == 0) {
output = 1;
break;
}
}
if(output == 0)
{
sleep(1);
}
return output;
}
void thread(myTest * pMyTest) {
printf("Begin threadID=%u run!\n", pMyTest->threadID);
int index, input, output;
int threadID = pMyTest->threadID;
int dataNum = 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; 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
(inMyTest+i)->threadID = i;
}
pthread_t * tid = (pthread_t*)malloc(sizeof(pthread_t)*threadNum);
printf("Begin create pthread.\n");
for(i=0; i
if(ret != 0) {
printf("Create pthread error.\n");
return 0;
}
}
for(i=0; i
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;
}
#include
#include
typedef struct myTestType
{
int threadID;
int threadNum;
int dataNum;
int *input;
int *output;
int *index;
int *primeNum;
pthread_mutex_t *pMutIndex;
}myTest;
int calculate(int input) {
int i;
int output = 0;
for(i=2; i if(input % i == 0) {
output = 1;
break;
}
}
if(output == 0)
{
sleep(1);
}
return output;
}
void thread(myTest * pMyTest) {
printf("Begin threadID=%u run!\n", pMyTest->threadID);
int index, input, output;
int threadID = pMyTest->threadID;
int dataNum