-1
Hello, I have a problem, I have a college assignment where I have a very large vector, where I have to get each processor thread through a part of that vector increasing the speed of the search, but when I run my code, appears 2 times the printf of the value in vector 0, I do not know pq, I believe must be occurring some race condition yet, but I do not know where.
#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#define TAM 100000000
long *vetor;
long cont=0;
int vet[3];
sem_t semaforo;
void preencher(){
long i;
srand( (unsigned)time(NULL) );
for(i=0;i<TAM;i++) vetor[i]=rand()%TAM;
}
void contar(void *argp) {
int i, temp;
int alvo;
alvo = (long) argp;
sem_wait(&semaforo);
vet[0] = (TAM/4);
printf("VALOR NO VETOR[0]=%d\n", vet[0]);
for (i = 0; i < vet[0]; i++) {
if(vetor[i]==alvo){
temp = cont;
temp++;
cont = temp;
}
}
sem_post(&semaforo);
}
void contar2(void *argp) {
int i, temp;
int alvo;
alvo = (long) argp;
sem_wait(&semaforo);
vet[1] = (TAM/2);
printf("VALOR NO VETOR[1]=%d\n", vet[1]);
for (i = vet[0]; i < vet[1]; i++) {
if(vetor[i]==alvo){
temp = cont;
temp++;
cont = temp;
}
}
sem_post(&semaforo);
}
void contar3(void *argp) {
int i, temp;
int alvo;
alvo = (long) argp;
sem_wait(&semaforo);
vet[2] = (TAM/4)*3;
printf("VALOR NO VETOR[2]=%d\n", vet[2]);
for (i = vet[1]; i < vet[2]; i++) {
if(vetor[i]==alvo){
temp = cont;
temp++;
cont = temp;
}
}
sem_post(&semaforo);
}
void contar4(void *argp) {
int i, temp;
int alvo;
alvo = (long) argp;
sem_wait(&semaforo);
for (i = vet[2]; i < TAM; i++) {
if(vetor[i]==alvo){
temp = cont;
temp++;
cont = temp;
}
}
sem_post(&semaforo);
}
int main(int argc, char * argv[])
{
pthread_t t1, t2, t3, t4;
sem_init(&semaforo,0,1);
long chave;
vetor = (long *)malloc(TAM*sizeof(long));
preencher();
printf("\nDigite a chave a ser buscada no vetor:\n");
scanf("%ld",&chave);
contar((void *)chave);
int rc;
rc = pthread_create(&t1, NULL, (void *)contar, NULL);
rc = pthread_create(&t2, NULL, (void *)contar2, NULL);
rc = pthread_create(&t3, NULL, (void *)contar3, NULL);
rc = pthread_create(&t4, NULL, (void *)contar4, NULL);
rc = pthread_join(t1, NULL);
rc = pthread_join(t2, NULL);
rc = pthread_join(t3, NULL);
rc = pthread_join(t4, NULL);
printf("Ocorrencias: %ld",cont);
return(0);
}